如何在Windows Universal App中读取文本文件

编程入门 行业动态 更新时间:2024-10-28 02:28:09
本文介绍了如何在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中读取文本文件

本文发布于:2023-11-06 04:18:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   如何在   Universal   Windows   App

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!