2011-07-06 116 views
2

我正在開發一個C#應用程序,將需要刪除一些文件在System32中,和我做了以下內容:刪除文件C#

File.Delete(@"c:\windows\system32\<file>"); 

這不是工作,它不會拋出異常,但它也不會刪除文件。我認爲它與權限有關,但我不知道如何解決它。你能幫我嗎?

+8

我很難想象從system32目錄中刪除某些內容的合理原因。你想達到什麼目的? –

+1

你是否有機會在x64計算機上使用x86? – Mehrdad

+0

我只是試圖刪除一個示例.txt文件,我使自己在System32文件夾中,並得到一個UnauthorizedAccessException ...不知道爲什麼你不會呢? – aardvarkk

回答

1

如果你在Vista或7(或Server 2008+)上執行此操作,UAC也會阻礙你的刪除操作。在這種情況下,你需要修改你的應用程序的清單,以便它提升其權限啓動時(或啓動提升的子應用程序或過程):

http://victorhurdugaci.com/using-uac-with-c-part-1/

而且,這將是如果您發佈了您所遇到的異常,這會很有幫助,因爲這會提示它是否與權限相關,與x64相關還是UAC。

2

好吧,讓我們假設你沒有做惡意的東西;) 無論如何,還沒有嘗試過,但模擬會有所幫助。

谷歌模擬c#,你會看到很多的例子,並且郵件的想法很簡單:你的代碼通常在你的用戶的權限下運行。通過模擬,您可以在另一個用戶的權限下運行您的代碼(以編程方式,用戶不需要執行任何操作)。因此,如果用戶可以直接訪問該文件夾而沒有UAC restirction,那麼理論上應該只是運行。但是,我還沒有嘗試過,所以如果它不起作用,不要生氣。只是一個想法。

0

您需要管理員權限才能修改該文件夾中的文件。在屬性中使用app.manifest文件,如下所示:

<?xml version="1.0" encoding="utf-8"?> 
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <assemblyIdentity version="1.0.0.0" name="YourApplication.app" /> 
    <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> 
    <security> 
     <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> 
     <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 
     </requestedPrivileges> 
     <applicationRequestMinimum> 
     <defaultAssemblyRequest permissionSetReference="Custom" /> 
     <PermissionSet ID="Custom" SameSite="site" Unrestricted="true" /> 
     </applicationRequestMinimum> 
    </security> 
    </trustInfo> 
    <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> 
    <application> 
     <!-- A list of all Windows versions that this application is designed to work with. Windows will automatically select the most compatible environment.--> 
     <!-- If your application is designed to work with Windows 7, uncomment the following supportedOS node--> 
     <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>--> 
    </application> 
    </compatibility> 
    <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) --> 
    <!-- <dependency> 
    <dependentAssembly> 
     <assemblyIdentity 
      type="win32" 
      name="Microsoft.Windows.Common-Controls" 
      version="6.0.0.0" 
      processorArchitecture="*" 
      publicKeyToken="789cf14ab782c1eb" 
      language="*" 
     /> 
    </dependentAssembly> 
    </dependency>--> 
</asmv1:assembly>