C# 未以管理员身份打开IDE会导致FileStream抛出对路径的访问被拒绝异常
正如标题所说,如果我以管理员的身份打开VisualStudioIDE,FileStream就可以正常工作。但如果我不是以管理员身份运行,它会拒绝访问路径“C:\\ABCD.ddthp”。但是如果我在C目录中选择一个文件夹,它就可以正常工作。例如,如果路径为“C:\ABCFolder\ABCD.ddthp”,则可以正常工作。这是我的密码。是否有任何解决方法,或者IDE是否应该作为管理员打开C# 未以管理员身份打开IDE会导致FileStream抛出对路径的访问被拒绝异常,c#,filestream,C#,Filestream,正如标题所说,如果我以管理员的身份打开VisualStudioIDE,FileStream就可以正常工作。但如果我不是以管理员身份运行,它会拒绝访问路径“C:\\ABCD.ddthp”。但是如果我在C目录中选择一个文件夹,它就可以正常工作。例如,如果路径为“C:\ABCFolder\ABCD.ddthp”,则可以正常工作。这是我的密码。是否有任何解决方法,或者IDE是否应该作为管理员打开 try { if (File.Exists(pat
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:\drive,选择properties,然后选择security选项卡,并授予您的帐户写访问权限来授予自己权限
或者,使用更好的位置解决方法是不要直接写入
C:
驱动器或任何其他需要管理访问权限的位置。根据文件的用途,通常有三个候选位置:
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();
}
输出
这只意味着您需要以管理员身份运行才能写入C:驱动器的根目录。操作系统需要管理员权限才能在系统磁盘的根目录中写入文件。别把文件写在那里,我不明白为什么要投反对票。我编辑了我的问题,询问是否存在解决方法。