简体   繁体   English

C#使用带有DownloadFileAsync的StreamReader从文件读取行

[英]C# read line from file with StreamReader with DownloadFileAsync

I am having a problem reading file with StreamReader and while line != null add to textBox1 我在使用StreamReader读取文件时遇到问题,而line != null添加到textBox1

Code: 码:

using(StreamReader reader = new StreamReader("lastupdate.txt"))
{
    string line;

    while((line = reader.ReadLine()) != null)
    {
        textBox1.Text = line;
    }

    reader.Close();
}

It's not working and I don't know why. 它不起作用,我不知道为什么。 I tried to use using StreamReader , I download the file from the URL and I can see in the folder that the file is downloaded. 我尝试using StreamReader ,我从URL下载文件,我可以在文件夹中看到该文件已下载。 The lastupdate.txt is 1KB in size. lastupdate.txt大小为1KB。

This is my current working code with MessageBox . 这是我目前使用MessageBox工作代码。 If I remove the MessageBox , the code doesn't work. 如果我删除MessageBox ,代码不起作用。 It needs some kind of wait or I don't know: 它需要某种等待或我不知道:

WebClient client = new WebClient();

client.DownloadFileAsync(new Uri(Settings.Default.patchCheck), "lastupdate.txt"); // ok

if(File.Exists("lastupdate.txt"))
{
    MessageBox.Show("Lastupdate.txt exist");
    using(StreamReader reader = new StreamReader("lastupdate.txt"))
    {
        string line;

        while((line = reader.ReadLine()) != null)
        {
            textBox1.Text = line;
            MessageBox.Show(line.ToString());
        }

        reader.Close();
    }

    File.Delete("lastupdate.txt");
}

Try : 试试:

StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("lastupdate.txt")) 
{
    while (sr.Peek() >= 0) 
    {
        sb.Append(sr.ReadLine());
    }
}
textbox.Text = sb.Tostring();

If you want the text in the text box it would be much more effective to read all of it and then put it into the text box: 如果您想要文本框中的文本,那么阅读所有文本然后将其放入文本框会更有效:

var lines = File.ReadAllLines("lastupdate.txt");
textBox1.Lines = lines; //assuming multi-line text box

or: 要么:

textBox1.Text = File.ReadAllText("lastupdate.txt");

Edit: 编辑:

After latest update - you are downloading the file asynchronously - it might not even be there, only partially there or in a state in-between when your code executes. 在最新更新之后 - 您正在异步下载文件 - 它甚至可能不在那里,只是部分存在或在代码执行时处于中间状态。

If you just want the text string in the file don't download it, use DownloadString instead: 如果您只想让文件中的文本字符串不下载,请改用DownloadString

string text = "";
using (WebClient wc = new WebClient())
{
    text = wc.DownloadString(new Uri(Settings.Default.patchCheck));
}
textBox1.Text = text;

Try this : 试试这个 :

using(StreamReader reader = new StreamReader(Path))
{
    string line =  reader.ReadLine();

    while(line != null)
    {
        textBox1.Text += line;
        line = reader.ReadLine()
    }

    reader.Close();
}

Web Client has a rather bizarre DownloadFileAsync method. Web客户端有一个相当离奇的DownloadFileAsync方法。 The return type is void, so it is not awaitable. 返回类型无效,因此无法等待。 Also, that means we do not even get a Task, so ContinueWith is not possible. 此外,这意味着我们甚至没有得到任务,所以ContinueWith是不可能的。 That leaves us with using the DownloadFileCompleted event. 这让我们使用了DownloadFileCompleted事件。

const string FileName = "lastupdate.txt";

private void DownloadLastUpdate() {
    var client = new WebClient();

    client.DownloadFileCompleted += ( s, e ) => {
        this.UpdateTextBox( e.Error );
        client.Dispose();
    };

    client.DownloadFileAsync( new Uri( Settings.Default.patchCheck ), FileName );
}

I went with an optional exception parameter to relay any exception messages. 我使用可选的异常参数来中继任何异常消息。 Feel free to refactor as desired. 随意按照需要重构。 File.ReadLines yields text line by line, so large files should not use very much memory. File.ReadLines逐行生成文本,因此大文件不应使用太多内存。

private void UpdateTextBox( Exception exception = null ) {
    textBox1.Text = string.Empty;

    if ( exception != null ) {
        textBox1.Text = exception.Message;
        return;
    }

    if ( !File.Exists( FileName ) ) {
        textBox1.Text = string.Format( "File '{0}' does not exist.", FileName );
        return;
    }

    var lines = File.ReadLines( FileName );

    textBox1.Text = string.Join( Environment.NewLine, lines );
}

上面给出的答案是正确的,但在你的代码中,只需更改1行:

textBox1.Text += line;

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

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