首页 文章

尝试将json文件写入app目录时,UWP“拒绝访问路径'…'”

提问于
浏览
0

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

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

这是我使用的代码:

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

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

2 回答

  • 0

    问题是您尚未在 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>
    

    请注意,除了指定功能外,还必须添加 rescap 命名空间,并将其添加到 gnorableNamespaces

  • 0

    以下是我为我的应用程序记录内部文件的方法:

    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();
        }
    }
    

    希望这可以帮助

相关问题