【问题标题】:UWP "Access to the path '...' is denied" when trying to write a json file to the app directory尝试将json文件写入应用程序目录时,UWP“拒绝访问路径'...'”
【发布时间】:2019-01-28 09:54:57
【问题描述】:

我是 UWP 新手,但我已经使用 C#(桌面应用程序等)很长时间了。我最近尝试像往常一样写入 app 目录中的 json 文件,我收到了这条消息:

Access to the path 'C:\...\setting.json' is denied

这是我使用的代码:

File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "setting.json"), JsonConvert.SerializeObject(Settings));

我觉得这很奇怪,所以我做了一些研究。应用程序目录似乎是只读的。我尝试将属性设置为“正常”,仍然是同样的错误。我试过使用 StorageFolder 和 StorageFile,还是一样的信息。有没有办法使文件夹不是只读的?这在 WPF 应用程序中工作得很好......

【问题讨论】:

  • 您不应该将文件放在您的应用程序目录中。仅仅因为它在 WPF 中“有效”并不意味着它是正确的。 Storing and retrieving settings 上有一个专为 UWP 开发人员编写的页面。 (另外,假设当前目录是有意义的,通常是一种自责的好方法。在早期启动之外,假设它没有指向任何有用的地方是最安全的)

标签: c# uwp


【解决方案1】:

问题是你没有在Package.appxmanifest 文件中声明broadFileSystemAccess 能力。并且broadFileSystemAccess 允许用户有权访问的所有文件。例如:文档、图片、照片、下载、桌面、OneDrive等。

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

请注意,除了指定capability之外,rescap命名空间一定要加上,gnorableNamespaces也要加上

【讨论】:

    【解决方案2】:

    这是我为我的应用程序内部记录文件的方式:

    Windows.Storage.ApplicationDataContainer roamingSettings;
    Windows.Storage.StorageFolder roamingFolder;
    string donnees = Newtonsoft.Json.JsonConvert.SerializeObject(anobject);
    if (UseRoaming)
    {
        roamingFolder = Windows.Storage.ApplicationData.Current.RoamingFolder;
        roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
    }
    else
    {
        roamingFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
    }
    StorageFile sampleFile = await roamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    
    using (IRandomAccessStream textStream = await sampleFile.OpenAsync(FileAccessMode.ReadWrite))
    {
        using (DataWriter textWriter = new DataWriter(textStream))
        {
            textWriter.WriteString(donnees);
            await textWriter.StoreAsync();
        }
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 2010-12-27
      • 2015-03-06
      • 2015-03-19
      • 2017-08-05
      • 2016-04-05
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多