【问题标题】:File.Exists returns true, but File.Encrypt throwsFile.Exists 返回 true,但 File.Encrypt 抛出
【发布时间】:2020-09-11 11:30:00
【问题描述】:

我第一次在我的 Windows Server 2016 上部署了新的 ASP.NET Core 3.1 应用程序。但是,应用程序在启动时崩溃,并在 appsettings.json 加密期间引发 500.30 错误和异常。正如您在下面的 sn-p 中看到的,File.Exists 返回 true,但是,在 File.Encrypt 中会引发异常。我已确保在 IIS 的应用程序池中定义的用户帐户对文件夹具有完全控制权,但它似乎没有任何效果。

    private static void EncryptAppSettings()
    {
        var path = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
        if (File.Exists(path))
        {
            File.Encrypt(path); // Unhandled exception. System.IO.IOException: Element not found. : 'P:\Balsam\appsettings.json'
        }
    }

文件本身当然存在于指定路径下。 来自事件查看器的完整信息:

Application: Balsam.Front.exe
CoreCLR Version: 4.700.20.41105
.NET Core Version: 3.1.8
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.IOException: Element not found. : 'P:\Balsam\appsettings.json'
   at System.IO.FileSystem.ThrowExceptionEncryptDecryptFail(String fullPath)
   at System.IO.FileSystem.Encrypt(String path)
   at System.IO.File.Encrypt(String path)
   at Balsam.Front.Program.EncryptAppSettings() in P:\JENKINS\x\Balsam.Front\Program.cs:line 40
   at Balsam.Front.Program.Main(String[] args) in P:\JENKINS\x\Balsam.Front\Program.cs:line 16

如果File.Exists 返回true,为什么File.Encrypt 会抛出异常?

【问题讨论】:

  • 这是一个seemingly related bug in .Net Core(虽然现在应该已经修复了)。
  • 服务用户拥有文件夹/文件的读取和写入权限?
  • @Fildor 是的,我可以设置的每个权限都已设置。

标签: c# asp.net-core io


【解决方案1】:

不要认为问题出在您根据文档编写的代码上。

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.exists?view=netcore-3.1 https://docs.microsoft.com/en-us/dotnet/api/system.io.file.encrypt?view=netcore-3.1

特别阅读 File.Encrypt 抛出的异常,当它是一个 IO 异常时,问题不在于找不到文件(它有很多其他异常)。

IOException 打开文件时发生 I/O 错误。

-或-

当前平台不支持此操作。

所以,不太确定问题出在哪里。 File.Encrypt 引发的所有其他常见问题都有例外,所以我猜这个问题完全是另外一回事。

也许这是 .NET Core 中的一个错误,类似于 cmets 中提到的错误?也许 .NET 需要的服务之一存在问题?无论哪种方式,据我所知,我们都无法明确解决此错误。

我会在 git 上提出一个错误。也许将其链接到此答案中,以便将来遇到此问题的人有更多的可见性,如果这是您选择的路径。

【讨论】:

  • 我创建了问题。如果出现任何解决方案,如果提供任何解决方案,我将在稍后添加它作为答案。 github.com/dotnet/core/issues/5192
  • 正如您在对问题的评论中看到的,问题与 .NET 本身无关,因为它是来自 WinAPI 的默认消息。一旦系统管理员找到根本原因,我将跟进解决方案。
  • 有了NetMage提到的EncryptFileW,你可以参考this。也许你能找到一些有用的东西。
猜你喜欢
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多