C# UWP“;访问路径'';“被拒绝”;尝试将json文件写入应用程序目录时

C# UWP“;访问路径'';“被拒绝”;尝试将json文件写入应用程序目录时,c#,uwp,C#,Uwp,我是UWP新手,但我已经使用C#(桌面应用程序等)很长时间了。我最近像往常一样尝试在app目录中写入一个json文件,我得到了以下消息: Access to the path 'C:\...\setting.json' is denied 这就是我使用的代码: File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "setting.json"), JsonConvert.SerializeObject(Settings)

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

Access to the path 'C:\...\setting.json' is denied
这就是我使用的代码:

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

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

问题在于您尚未在
Package.appxmanifest
文件中声明功能。和
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

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

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

希望这有帮助

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