簡體   English   中英

從應用程序安裝文件夾的子文件夾中讀取文件

[英]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()

必須注意,如果我使用不帶子文件夾的文件,則一切正常。

您可以使用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"));

@"\\myfolder\\myfile.txt"; 如果其網絡路徑應為@"\\\\myfolder\\myfile.txt"; 如果是本地文件,則需要驅動器號,即。 @"c:\\myfolder\\myfile.txt";

但是,GetFileAsync的文檔顯示子文件夾中的文件為@"myfolder\\myfile.txt"

當您使用不帶子文件夾的文件名時,它將在當前文件夾中查找。

我認為您需要使用:

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

文件名中的點代表當前文件夾。 如果要指定使用相對路徑,則@"\\myfolder\\myfile.txt"不正確。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM