【问题标题】:Unable to access file using .Net Core 3 or .Net Framework on Windows 10无法在 Windows 10 上使用 .Net Core 3 或 .Net Framework 访问文件
【发布时间】:2021-01-16 08:30:48
【问题描述】:

我的 VS 2019 生成的新项目无法读取或写入文件。即使是下面的简单代码也不起作用。

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("hello");

        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        var folder = Path.GetDirectoryName(path);

        var filePath = Path.Combine(folder, "test.txt");
        Console.WriteLine(filePath);
        
        // File.WriteAllLines(filePath, new[] { "hello" });
        
        using (var f = new FileStream(filePath, FileMode.OpenOrCreate))
        {
            f.Write(new byte[] { 0x39 }, 0, 1);
        }
    }
}

使用访问文件

  • .Net Core 3.0 + 调试器
  • .Net Core 3.0 + 生成的exe
  • .Net Framework 4.6.2, 4.8(其他的没测试过)

给出异常

Unhandled exception. System.UnauthorizedAccessException: Access to the path 'C:\Users\user\Documents\ConsoleApp1\ConsoleApp1\Debug\netcoreapp3.1\test.txt' is denied.

但是,它适用于 .Net Core 2.2 或更低版本或使用 dotnet ConsoleApp1.dll

我其他几年的项目工作。我以前从未遇到过这样的问题。是什么问题以及如何解决?

【问题讨论】:

  • Docs 表示当文件为只读时将抛出UnauthorizedAccessException。您可以添加FileAccess.ReadFileAccess.ReadWrite
  • 我试过FileAccess,但它是一样的。文件未创建。
  • 您的代码确实有效。必须有另一个应用程序正在使用该文件,否则该文件夹是只读的。

标签: c# .net windows .net-core visual-studio-2019


【解决方案1】:

原来我的防病毒软件阻止了文件访问。第一天没有弹出窗口,所以我不知道。后来,终于有弹窗了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2021-09-12
    • 2019-02-23
    相关资源
    最近更新 更多