【问题标题】:Access to the path is denied even when i run the application as administrator? [duplicate]即使我以管理员身份运行应用程序,也拒绝访问路径? [复制]
【发布时间】:2012-10-23 15:35:30
【问题描述】:

在下面的代码中,我试图从正在运行的应用程序中提取一个 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:\,但我总是收到此异常消息
怎么解决?

【问题讨论】:

  • 您写信给C:\Windows\System32,因为您明确使用了Environment.SystemDirectory;如果你写信给`D:`,我认为你不会看到这个问题。你跑高架了吗?请记住,在 Windows 中,“管理员用户”和“以管理员身份运行”是有区别的。

标签: c# .net


【解决方案1】:

您正在使用Environment.SystemDirectory,这就是它试图在那里保存的原因。但是,即使您在管理员用户下运行,某些系统文件夹也会受到保护。 system32 文件夹就是其中之一。您必须暂时关闭 UAC 才能以编程方式在其中保存某些内容,这并不是一件好事。

我强烈建议您找到一种不同/更好的方法来做到这一点。

【讨论】:

  • 我试图将文件保存到另一个不受保护的目录中,例如 D:\\,但我收到拒绝访问错误??
  • @ShikataGaNai 试试Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);。这将保存到当前用户的“我的文档”文件夹,保证您具有写入权限。如果您仍然收到拒绝访问错误,那么您正在处理的事情不是显而易见的。
  • MyDocuments 的访问也被拒绝了?这怎么可能!
  • @ShikataGaNai 尝试将您的流调用更改为new FileStream(location, FileMode.Create, FileIOPermissionAccess.Write);。我有一个偷偷摸摸的怀疑你从来没有请求写权限。或者,或者另外,检查 FileStream.CanWrite 等于什么。
猜你喜欢
  • 2012-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2012-12-15
  • 2011-12-29
  • 1970-01-01
相关资源
最近更新 更多