我必须从.txt
文件中读取文本内容,此文件位于app安装文件夹中,在子文件夹中,根据Microsoft docs,我这样做:
private async void readMyFile()
{
// Get the app's installation folder.
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// Get a file from a subfolder of the current folder by providing a relative path.
string txtFileName = @"\myfolder\myfile.txt";
try
{
//here my file exists and I get file path
StorageFile txtfile = await appFolder.GetFileAsync(txtFileName);
Debug.WriteLine("ok file found: " + txtfile.Path);
//here I get the error
string text = await FileIO.ReadTextAsync(txtfile);
Debug.WriteLine("Txt is: " + text);
}
catch (FileNotFoundException ex)
{
}
}
错误是:
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.ni.dll
exception file not found: System.IO.FileNotFoundException: The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Smadshop.MainPage.<testExistsFile>d__8.MoveNext()
必须注意的是,如果我使用没有子文件夹的文件,一切正常。
答案 0 :(得分:4)
您可以使用URI
:
using Windows.Storage;
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appx:///file.txt");
所以在你的情况下它将是:
StorageFile txtfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///myfolder/myfile.txt"));
答案 1 :(得分:1)
@"\myfolder\myfile.txt";
如果网络路径应为@"\\myfolder\myfile.txt";
如果是本地文件则需要驱动器号,即@"c:\myfolder\myfile.txt";
但GetFileAsync的文档显示子文件夹中的文件为@"myfolder\myfile.txt"
当您使用不带子文件夹的文件名时,它将查找当前文件夹。
答案 2 :(得分:0)
我认为您需要使用:
string txtFileName = @".\myfolder\myfile.txt";
文件名中的点代表当前文件夹。如果您想使用相对路径指定,则@"\myfolder\myfile.txt"
不正确。
答案 3 :(得分:0)
GetFileAsync将采用folder/fileName
形式的相对路径。您也可以先获取文件夹而不是文件,或使用GetItemAsync
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// Get a file from a subfolder of the current folder
// by providing a relative path.
string image = @"Assets\Logo.scale-100.png";
var logoImage = await appFolder.GetFileAsync(image);