正如标题所说,如果我以管理员身份打开Visual Studio IDE,FileStream就可以了。但是,如果我不以管理员身份运行,则会拒绝访问路径“C:\\ ABCD.ddpp”。但是,如果我在C目录中选择一个文件夹,它可以正常工作。例如,如果路径是'C:\ ABCFolder \ ABCD.ddthp',它可以正常工作。这是我的代码。是否有任何解决方法或者IDE应该以Admin身份打开。
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;
}
答案 0 :(得分:0)
您的用户帐户没有权限写入您计算机的C:\驱动器,但管理员有。
您可以通过右键单击Windows资源管理器中的C:\驱动器,选择属性,然后选择安全选项卡并授予您的帐户写入权限来授予自己权限。
或者,使用更好的位置
答案 1 :(得分:0)
解决方法是不直接写入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();
}
<强>输出强>