2011-07-28 21 views
0

我已經創建安裝程序,需要刪除一些文件和文件夾,如果它們已經存在並用新的替換。無法刪除目錄和文件使用C#

當用戶點擊安裝時,安裝程​​序會提示輸入UAC。選擇是時,安裝程​​序將調用該方法刪除現有的文件和文件夾。但它無法刪除文件和文件夾。我正在使用的代碼是DI.Delete(路徑)。它,而如果我運行命令提示符以管理員身份,然後使用「MSIEXEC /我的setup.msi」命令,它會刪除這些文件和文件夾的給出了這個錯誤

Access to the path 'CodeCreate.aspx' is denied. 
    at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive) 
    at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive) 
    at System.IO.DirectoryInfo.Delete(Boolean recursive) 
    at CustomizationCA.CustomActions.DeleteExistingFilesAndFolder(Session session) 

而且當使用Directory.Delete(path,true);我得到這個例外

Exception thrown by custom action: 
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security. 
    at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly) 
    at System.Diagnostics.EventLog.SourceExists(String source, String machineName) 
    at System.Diagnostics.EventLog.VerifyAndCreateSource(String sourceName, String currentMachineName) 
    at System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte rawData) 
    at System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte rawData) 
    at System.Diagnostics.EventLog.WriteEntry(String source, String message) 
    at CustomizationCA.CustomActions.DeleteExistingFilesAndFolder(Session session) 

我使用WIX工具來創建安裝程序。

如果我去特定文件的屬性,然後給所有用戶的完全權限,然後嘗試刪除該文件,該文件被刪除。 enter image description here

回答

4

檢查文件夾或文件是否是隻讀的。首先將文件置於正常狀態。

使用此代碼刪除任何和每一個文件在你的目錄

File.SetAttribute(path, FileAttributes.Normal); 
File.Delete(path); 
+0

Saeed:我也使用了這個代碼,但它並沒有刪除文件。更多細節我已添加在我的文章中。 –

+1

那麼你爲什麼不使用**模擬**或**升級**進行刪除操作? –

+0

安裝開始時,安裝程​​序會提供UAC提示。所以權利必須通過所有方法。對? –

0

我不確定我是否理解你。你創建了一個安裝程序,它正在刪除一些文件。當安裝程序啓動時,它會提示輸入UAC。通過刪除文件,您將獲得SecurityException

您確定執行安裝程序的用戶有權刪除該文件。 如果他沒有這種權限,它不能工作,這是合乎邏輯的。而且你說如果你讓用戶完全控制,它就會工作。

如果你想要它的工作,你必須給予用戶刪除這些文件的權限。

(在特殊權限找到「刪除」權限)

2

您使用刪除的文件中的自定義操作必須推遲自定義操作,而且必須有冒充標誌設置爲「無」。否則,自定義操作將以啓用MSI安裝的用戶的特權運行,而不應用提升。


更好地考慮使用維克斯RemoveFolderEx元素來處理文件刪除,而不是自定義操作。