简体   繁体   English

用StreamReader逐行读取文件

[英]Reading a file with StreamReader line by line

I am trying to read a simple text file line by line in Windows 8 C# file with StreamReader. 我正在尝试使用StreamReader在Windows 8 C#文件中逐行读取一个简单的文本文件。 I tried many solutions but non of it worked. 我尝试了许多解决方案,但没有一个奏效。 Sometimes the file is read and sometimes it's not(the class is empty, only nulls). 有时读取文件,有时不读取(类为空,只有null)。 If the program is running it's never working but when I set up a debugger and use it to go line by line sometimes it works. 如果程序正在运行,它将永远无法运行,但是当我设置调试器并使用它逐行运行时,有时它会运行。 Why is that? 这是为什么? That's the source: 这就是来源:

public async void read(string fileName)
    {

        string File = Path.Combine(Package.Current.InstalledLocation.Path, "myfolder", fileName);

        StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(File));

        Stream s = await folder.OpenStreamForReadAsync(Path.GetFileName(File));
        StreamReader streamReader = new StreamReader(s);

        myClass.name = streamReader.ReadLine();
        myClass.desc = streamReader.ReadLine();
        myClass.number = int.Parse(streamReader.ReadLine());
        myClass.house = new House[myClass.number];

        for (int i = 0; i < myClass.number; i++)
        {
            myClass.house[i] = new House();
            myClass.house[i].name = streamReader.ReadLine();
            myClass.house[i].size = double.Parse(streamReader.ReadLine());
        }  
    }

You should only use async void if the function is an event handler (eg button press). 仅当函数是事件处理程序(例如,按下按钮)时,才应使用async void Generally, you should use async Task instead. 通常,应改为使用async Task

Change your method signature from void to Task : 将方法签名从void更改为Task

public async Task read(string fileName)

Then from your calling code, await it: 然后从您的调用代码中await

await yourclass.read("c:\\my_filename.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM