从应用程序安装文件夹的子文件夹中读取文件

Read file from subfolder of application installation folder

我必须从 .txt 文件中读取文本内容,该文件位于应用程序安装文件夹中的子文件夹中,根据 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()

必须注意,如果我使用没有子文件夹的文件,一切正常。

@"\myfolder\myfile.txt"; 如果它的网络路径应该是 @"\myfolder\myfile.txt"; 如果它是本地文件它需要一个驱动器号即 @"c:\myfolder\myfile.txt";

但是 GetFileAsync 的文档显示子文件夹中的文件是 @"myfolder\myfile.txt"

当您使用没有子文件夹的文件名时,它将在当前文件夹中查找。

我认为你需要使用:

string txtFileName = @".\myfolder\myfile.txt";

文件名中的点代表当前文件夹。在你想指定使用相对路径,那么@"\myfolder\myfile.txt"是不正确的。

GetFileAsync will take relative path in form folder/fileName. You can also get folder first and than file or use 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);

你可以用其他方式做到这一点,使用 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"));