【问题标题】:C# access to the path is denied...(System.UnauthorizedAccessException: Access to the path 'C:\' is denied.)C# 对路径的访问被拒绝...(System.UnauthorizedAccessException:对路径“C:\”的访问被拒绝。)
【发布时间】: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 块发送垃圾邮件?

标签: c# file


【解决方案1】:

通常 C 盘的访问被拒绝。 如果您仍想访问 C: Drive,请通过查看此参考将所有权更改为所有人。 https://www.techrepublic.com/article/how-to-change-ownership-of-files-and-folders-in-windows-10/

【讨论】:

    【解决方案2】:

    File.WriteAllText(pathc,modify); 行中,您尝试写入确定的文件,但看起来 var pathc 仅使用路径初始化(例如 E:\)。 我建议使用

    wathc = Path.Combine(pathc, wathc); 
    File.WriteAllText(wathc, modify);
    Console.WriteLine("DONE!");
    beggining();
    

    应该删除File.Move(pathc, wathc); 行,因为您已经拥有具有正确文件名和所需上下文的文件。

    【讨论】:

    • 是的,谢谢!它工作!根的访问权限只是被拒绝.....但是对其他路径的访问没有被拒绝但是我有一个 DirectoryNotFoundException .....我写了 E:/test/
    • 哪一行给你DirectoryNotFoundExceptionDirectory.Exists 条件应该检查​​这个(并检查)。
    【解决方案3】:

    尝试使用文件 С:\Test\p.txt 或 D:\Test\p.txt

    【讨论】:

      猜你喜欢
      • 2018-07-19
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      相关资源
      最近更新 更多