Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

c# - how to read a text file in windows universal app

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...