UWP App 不断抛出未授权访问异常

UWP App Keeps Throwing Unauthorized Access Exception

我正在制作一个 UWP 应用程序并且我一直有 System.UnauthorizedAccessException

这是我的主文件的完整代码

private void SaveButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var user = new Configuration();
            string Email = txtEmail.Text.Trim();

                user[Email]["Value"].StringValue = "test";

            string dest = Path.GetFullPath(@"C:\Users\IT\Desktop\AttendanceApp\AttendanceApp\bin\x86\Debug\AppX\Test\user.cfg");
            user.SaveToFile(dest);
        }

当我阅读 UWP 应用程序文件访问权限的文档时,它建议添加这一行

xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap mp uap5 rescap"> ...

这是我的 AppxManifest 文件

<Package xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap mp uap5 rescap" xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"  xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5">
---
  <Capabilities>
    <rescap:Capability Name="broadFileSystemAccess" />
  </Capabilities>

因此,当我尝试保存文件时。我仍然遇到这个错误。

System.UnauthorizedAccessException HResult=0x80070005
Message=Access to the path 'C:\Users\IT\Desktop\AttendanceApp\AttendanceApp\bin\x86\Debug\AppX\Test\user.cfg' is denied. Source=System.Private.CoreLib StackTrace: at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at SharpConfig.Configuration.SaveToFile(String filename, Encoding encoding) at SharpConfig.Configuration.SaveToFile(String filename) at AttendanceApp.MainPage.SaveButton_Click(Object sender, RoutedEventArgs e) in C:\Users\IT\Desktop\AttendanceApp\AttendanceApp\MainPage.xaml.cs:line 57

顺便说一句,我也在使用 SharpConfig 来编辑我的 .cfg 文件

知道为什么会这样吗?任何帮助都会很棒

有两个地方需要注意:

  1. 如@mm8 所说,您上面代码中的路径 C:\Users\IT\Desktop\AttendanceApp\AttendanceApp\bin\x86\Debug\AppX\ 等于 Windows.ApplicationModel.Package.Current.InstalledLocation.Path。在 UWP 中,已安装的 localtion 文件夹是只读的。您不能使用任何 API 在其中写入。你可以考虑将 'user.cfg' 复制到其他地方,然后你可以写信给它。 ApplicationData folder would be a good choice. For example, LocalFolder.
  2. 我看到您添加了 broadFileSystemAccess 功能来访问应用容器外的文件。太好了,但是您错过了 important prompt 'This capability works for APIs in the Windows.Storage namespace.'. I've checked the SharpConfig's source code, the SaveToFile 方法使用 'FileStream' 相关 API 来写入文件。它不包含在 'Windows.Storage Namespace' 中。因此,'broadFileSystemAccess' 功能不适用于它。

因此,如果您必须在项目中使用 'SharpConfig',则需要使用 'Windows.Storage Namespace' API 更改其源代码并为您的 UWP 项目编译自定义版本。同时,请记住我在第一段中的解释。