未以管理员身份打开 IDE 导致 FileStream 抛出对路径的访问被拒绝的异常

Not opening IDE as Admin causes FileStream throw access to the path is denied exception

正如标题所说,如果我以管理员身份打开 Visual Studio IDE,FileStream 工作正常。但是,如果我不 运行 作为管理员,它会拒绝访问路径 'C:\ABCD.ddthp'。但是,如果我 select C 目录中的一个文件夹,它就可以正常工作。例如,如果路径是 'C:\ABCFolder\ABCD.ddthp' 它工作正常。这是我的代码。是否有解决此问题的方法,或者 IDE 是否应该以管理员身份打开。

 try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

           //The following line causes an exception.

                using (var stream = new FileStream(path,
                    FileMode.CreateNew, FileAccess.Write).Encrypt())
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter);
                        jsonWriter.Formatting = Formatting.Indented;
                        protocolJObject.WriteTo(jsonWriter);
                    }
                }
                return ReturnCodes.Success;
            }
            catch (UnauthorizedAccessException ex)
            {
                SystemDebugLogLogger.LogError(ex, "Protocol: WriteJson");
                returnValue = ReturnCodes.FileAccessDenied;
            }

您的用户帐户无权写入您计算机的 C:\ 驱动器,但管理员有权限。

您可以通过右键单击 windows 资源管理器中的 C:\ 驱动器、select 属性和安全选项卡来授予自己权限,并授予您的帐户写入权限。

或者,使用更好的位置

解决方法是不直接写入 C: 驱动器,或任何其他需要管理权限的位置。根据文件的用途,通常有三个候选位置:

  1. 临时文件夹,用于存放不需要保存的文件
  2. AppData 文件夹,存放您的应用程序需要的文件,不同用户的文件可能不同
  3. 您的应用程序的安装位置

您可以获得以下文件夹:

private static void Main()
{
    // Create your own file name
    var fileName = "MyAppData.txt";

    // Get temp path
    var tempPath = Path.GetTempPath();

    // Get AppData path and add a directory for your .exe
    // To use Assembly.GetExecutingAssembly, you need to add: using System.Reflection
    var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    var exeName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
    var appDataForThisExe = Path.Combine(appDataFolder, exeName);
    Directory.CreateDirectory(appDataForThisExe);

    // Get the path where this .exe lives
    var exePath = Path.GetDirectoryName(
        new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

    // Now you can join your file name with one of the above paths
    // to construct the full path to the file you want to write
    var tempFile = Path.Combine(tempPath, fileName);
    var appDatFile = Path.Combine(appDataForThisExe, fileName);
    var exePathFile = Path.Combine(exePath, fileName);

    Console.WriteLine($"Temp file path:\n {tempFile}\n");
    Console.WriteLine($"AppData file path:\n {appDatFile}\n");
    Console.WriteLine($"Exe location file path:\n {exePathFile}");

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

输出