how to read a text file in windows universal app

天大地大妈咪最大 提交于 2019-11-27 23:14:52

the code is very simple, you just have to use a valid scheme URI (ms-appx in your case) and transform your WinRT InputStream as a classic .NET stream :

var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///thedata.txt"));
using (var inputStream = await file.OpenReadAsync())
using (var classicStream = inputStream.AsStreamForRead())
using (var streamReader = new StreamReader(classicStream))
{
    while (streamReader.Peek() >= 0)
    {
        Debug.WriteLine(string.Format("the line is {0}", streamReader.ReadLine()));
    }
}

For the properties of the embedded file, "Build Action" must be set to "Content" and "Copy to Ouput Directory" should be set to "Do not Copy".

You can't use classic .NET IO methods in Windows Runtime apps, the proper way to read a text file in UWP is:

var file = await ApplicationData.Current.LocalFolder.GetFileAsync("data.txt");
var lines = await FileIO.ReadLinesAsync(file);

Also, you don't need a physical path of a folder - from msdn :

Don't rely on this property to access a folder, because a file system path is not available for some folders. For example, in the following cases, the folder may not have a file system path, or the file system path may not be available. •The folder represents a container for a group of files (for example, the return value from some overloads of the GetFoldersAsync method) instead of an actual folder in the file system. •The folder is backed by a URI. •The folder was picked by using a file picker.

Haibara Ai

Please refer File access permissions for more details. And Create, write, and read a file provides examples related with File IO for UWP apps on Windows 10.

You can retrieve a file directly from your app's local folder by using an app URI, like this:

using Windows.Storage;

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appdata:///local/file.txt");  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!