UWP 中的 ReadLinesAsync 从绝对文件路径
问题描述:
我收到错误
文件名、目录名或卷标语法不正确.(来自 HRESULT 的异常:0x8007007B)
The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
我的代码是
public async void ReadFile()
{
var path = @"F:\VS\WriteLines.xls";
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(path);
var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);
foreach (var line in readFile.OrderBy(line =>
{
int lineNo;
var success = int.TryParse(line.Split(';')[4], out lineNo);
if (success) return lineNo;
return int.MaxValue;
}))
{
itemsControl.Items.Add(line);
}
}
错误显示在 var file = await folder.GetFileAsync(path);
答
您无法在 UWP 应用中从磁盘上的任意位置读取文件.您仍然可以通过多种方式完成任务:
You cannot read a file from an arbitrary location on disk in a UWP App. There are a couple of ways you can still accomplish your task:
- 您可以将 WriteLines.xls 文件添加到您的项目并将其构建操作设置为内容并将复制到输出目录设置为如果更新,请复制.然后,您只需将路径"值替换为: ,即可使用您拥有的代码访问该文件
- You can add the WriteLines.xls file to your project and set it's build action to Content and Copy to output Directory to Copy if newer. You can then access the file with the code you have by simply replacing the "path" value to:
var path = @"WriteLines.xls"
- 如果您需要能够从磁盘读取任何文件,您需要使用 FilePicker 选择文件或复制文档文件夹中的文件并将文件夹更改为:
var folder = KnownFolders.DocumentsLibrary;