【发布时间】:2021-04-02 00:36:34
【问题描述】:
我的 c# 程序有问题。
当我尝试创建文件时,程序抛出异常:
拒绝访问路径(System.UnauthorizedAccessException: Access to the path 'C:' is denied.
这是创建文件的代码:
static void crate()
{
try
{
Console.WriteLine("Specify the path where the file will be created");
string pathc = Console.ReadLine();//ask the path
if (pathc != "stop")
{
Console.WriteLine("Now specify the file name ");
string wathc = Console.ReadLine();//ask the file name for the new file
if (wathc != "stop")
{
if (Directory.Exists(pathc))//check if the path exist
{
Console.WriteLine("SPECIFY THE CONTENT OF FILE!");
string modify = Console.ReadLine();//the content of the file
if(modify != "stop")
{
File.WriteAllText(pathc,modify);/here there is a exception
Console.WriteLine("DONE!");
File.Move(pathc, wathc);
beggining();
}
else
{
beggining();
}
}
else
{
Console.WriteLine("The specified path doesn't exist\n");
beggining();
}
}
else
{
beggining();
}
}
else
{
beggining();
}
}
catch (Exception e)
{
Console.WriteLine("NO! the file maybe exist....retry please ex:C:/p.txt ({0})\n", e.GetBaseException());
beggining();
}
}
【问题讨论】:
-
在 Windows 上,您需要管理员权限才能修改 C:\ 中的文件。尝试使用管理员权限启动您的程序或(更好)使用不同的位置。
-
如果我没记错的话,你在所有可能的情况下都调用
beggining();,为什么不在你的例程结束时调用它而不是向那些 else 块发送垃圾邮件?