File.Exists returns 正确,但 File.Encrypt 抛出

File.Exists returns true, but File.Encrypt throws

我第一次在 Windows Server 2016 上部署了新的 ASP.NET Core 3.1 应用程序。但是,应用程序在启动时崩溃并在 appsettings.json 加密期间抛出 500.30 错误和异常。正如您在下面的代码片段中看到的,File.Exists returns 是正确的,但是,在 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 returns 为真,为什么 File.Encrypt 抛出异常?

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

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 An I/O error occurred while opening the file.

-or-

This operation is not supported on the current platform.

所以,不太确定是什么问题。 File.Encrypt 抛出的所有其他常见问题都有例外,所以我想这个问题完全是另外一回事。

也许这是 .NET Core 中的一个错误,类似于评论中提到的错误?也许 .NET 需要的其中一项服务有问题?无论哪种方式,据我所知,这个错误都不是我们可以明确解决的问题。

我会在 git 上提出错误。也许 link 在这个答案中,如果你选择了这条路,那么未来遇到这个问题的人会有更多的可见性。