2012-10-23 31 views
1

下面的代碼中,我試圖從正在運行的應用程序的DLL文件,並將其保存到System32目錄:即使我以管理員身份運行應用程序,對該路徑的訪問也會被拒絕?

using System; 
    using System.Collections.Generic; 
    using System.Text; 
    using System.IO; 
    using System.Diagnostics; 
    using Microsoft.VisualBasic; 
    using System.Security.Cryptography; 
    using System.Runtime.InteropServices; 
    using System.Reflection; 
    using System.Windows.Forms; 

    namespace ConsoleApplication1 
{ 
class Program 
{ 

    public static void ExtractSaveResource(String filename, String location) 
    { 
     // Assembly assembly = Assembly.GetExecutingAssembly(); 
     Assembly a = Assembly.GetExecutingAssembly(); 
     // Stream stream = assembly.GetManifestResourceStream("Installer.Properties.mydll.dll"); // or whatever 
     // string my_namespace = a.GetName().Name.ToString(); 
     Stream resFilestream = a.GetManifestResourceStream(filename); 
     if (resFilestream != null) 
     { 
      try 
      { 
       BinaryReader br = new BinaryReader(resFilestream); 
       FileStream fs = new FileStream(location, FileMode.Create); // say 
       BinaryWriter bw = new BinaryWriter(fs); 
       byte[] ba = new byte[resFilestream.Length]; 
       resFilestream.Read(ba, 0, ba.Length); 
       bw.Write(ba); 
       br.Close(); 
       bw.Close(); 
       resFilestream.Close(); 
      } 
      catch (Exception E) { MessageBox.Show(E.Message); } 
     } 
     // this.Close(); 

    } 

    static void Main(string[] args) 
    { 
     string systemDir = Environment.SystemDirectory; 
     ExtractSaveResource("MySql.Data.dll",systemDir); 

    } 
} 
} 

異常消息:

Access to the path C:\Windows\System32 is denied 

我試圖把文件複製到其他目錄像D:\或X:\但我總是得到這個異常消息
這怎麼解決?

+3

由於您明確使用了'Environment.SystemDirectory',因此您正在寫入'C:\ Windows \ System32';如果你寫信給'D:\'我不認爲你會看到這個問題。你在跑步嗎?請記住,在Windows中,「管理員用戶」和「以管理員身份運行」存在差異。 –

回答

1

你正在使用Environment.SystemDirectory,這就是爲什麼它試圖保存在那裏。但是,即使您在管理員用戶下運行,某些系統文件夾也會受到保護。 system32文件夾就是其中之一。你將不得不暫時關閉UAC來以編程方式保存某些內容,這不是一件好事。

我強烈建議您找到一種不同的/更好的方法來做到這一點。

+0

我試圖將文件保存到另一個非受保護的目錄,如D:\\但我得到一個訪問被拒絕的錯誤?? –

+0

@ShikataGaNai嘗試'Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);'。這將保存到當前用戶的「我的文檔」文件夾中,您可以在其中保證寫入權限。如果您仍然遇到訪問被拒絕的錯誤,那麼您正在處理的不是顯而易見的內容。 – tmesser

+0

對MyDocuments的訪問也被拒絕?這怎麼可能! –

相關問題