如何在Windows Universal App中读取文本文件 [英] how to read a text file in windows universal app
问题描述
我正在尝试读取一个名为thedata.txt的文本文件,其中包含要在want子手游戏中使用的单词列表。我尝试了不同的方法,但无法确定文件的放置位置,甚至根本无法确定应用程序何时运行。我已将文件添加到项目中,并且尝试将构建属性设置为内容,然后嵌入资源,但找不到该文件。我做了一个Windows 10通用应用程序项目。我尝试的代码如下:
I am trying to read a text file named thedata.txt that has a list of words that I want to use in a hangman game. I have tried different ways, but I can't figure out where the file gets placed, if at all when the app runs. I added the file to my project, and I have tried setting the build properties to content, and then embedded resource, but can't find the file. I have made a Windows 10 universal app project. The code I tried looks like this:
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());
}
}
我得到了例外。
我还尝试列出另一个目录中的文件:
I get exceptions. I also tried to list the files in another directory:
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);
}
我也看不到文件...我想避免在我的程序中硬编码名称列表。我不确定文件的放置路径。
I don't see the file there either...I want to avoid hard coding the list of names in my program. I'm not sure what the path that the file is placed.
推荐答案
代码很简单,您只需要使用有效的方案URI(在您的情况下为ms-appx),并将WinRT InputStream转换为经典的.NET流:
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()));
}
}
对于嵌入式文件的属性,生成操作必须设置为内容,复制到Ouput目录应该设置为请勿复制。
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".
这篇关于如何在Windows Universal App中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!