我正在尝试使用 UWP 访问 SD 卡。我使用的是 Windows 10。我已进入 Package.appxmanifest ...
在“功能”下,我检查了“可移动存储”
在声明下,我添加了文件类型关联。名称为“txt”,文件类型为“.txt”。相关部分...
<Extensions>
<uap:Extension Category="windows.fileTypeAssociation">
<uap:FileTypeAssociation Name="txt">
<uap:DisplayName>text</uap:DisplayName>
<uap:SupportedFileTypes>
<uap:FileType>.txt</uap:FileType>
</uap:SupportedFileTypes>
</uap:FileTypeAssociation>
</uap:Extension>
</Extensions>
我创建文本文件的代码...
string fileName = @"D:\test.txt";
using (FileStream fs = File.Create(fileName))
{
Byte[] text = new UTF8Encoding(true).GetBytes("testing");
fs.Write(text, 0, text.Length);
}
每次的结果都是“访问路径‘D:\text.txt’被拒绝”
我可以手动创建文件并将其复制到此目录。那么,为什么我无法使用 UWP 创建文件?我遵守了所有规则。我错过了什么吗?
最佳答案
您无法使用 File.Create()
访问受限 UWP 应用中的文件。您需要使用 Windows.Storage
命名空间中的功能。
private async void Test()
{
string filePath = @"D:\";
string fileName = @"Test.txt";
// get StorageFile object
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(filePath);
StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
// Open Stream and Write content
using (Stream stream = await file.OpenStreamForWriteAsync())
{
Byte[] text = new UTF8Encoding(true).GetBytes("testing");
await stream.WriteAsync(text, 0, text.Length);
}
}
关于c# - 访问 SD 卡被拒绝 - UWP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54330182/