如何在 windows 通用应用程序中读取文本文件

how to read a text file in windows universal app

我正在尝试读取一个名为 thedata.txt 的文本文件,其中包含我想在刽子手游戏中使用的单词列表。我尝试了不同的方法,但我无法弄清楚文件的放置位置,如果在应用程序运行时根本没有。我将该文件添加到我的项目中,并尝试将构建属性设置为内容,然后设置为嵌入资源,但找不到该文件。我做了一个 Windows 10 通用应用程序项目。我试过的代码如下所示:

  Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("thedata.txt");
            using (StreamReader inputStream = new StreamReader(stream))
            {
                while (inputStream.Peek() >= 0)
                {
                    Debug.WriteLine("the line is ", inputStream.ReadLine());
                }
            }

我得到例外。 我还尝试列出另一个目录中的文件:

 string path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
            Debug.WriteLine("The path is " + path);
            IReadOnlyCollection<StorageFile> files = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFilesAsync();
            foreach (StorageFile file2 in files)
            {
                Debug.WriteLine("Name 2 is " + file2.Name + ", " + file2.DateCreated);
            }

我在那里也没有看到该文件...我想避免在我的程序中对名称列表进行硬编码。我不确定文件的放置路径。

您不能在 Windows 运行时应用程序中使用经典的 .NET IO 方法,在 UWP 中读取文本文件的正确方法是:

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

此外,您不需要文件夹的物理路径 - 来自 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.

详情请参考File access permissions。 并且 Create, write, and read a file 在 Windows 10.

上提供了与 UWP 应用程序的文件 IO 相关的示例

您可以使用应用 URI 直接从应用的本地文件夹中检索文件,如下所示:

using Windows.Storage;

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appdata:///local/file.txt");  

代码非常简单,您只需使用有效的方案 URI(ms-appx 在您的情况下)并将您的 WinRT InputStream 转换为经典的 .NET 流:

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

对于嵌入文件的属性,"Build Action"必须设置为"Content","Copy to Ouput Directory"应设置为"Do not Copy"。