【问题标题】:C# read line from file with StreamReader with DownloadFileAsyncC# 使用 StreamReader 和 DownloadFileAsync 从文件中读取行
【发布时间】:2012-03-14 23:35:59
【问题描述】:

我在使用StreamReader 读取文件时遇到问题,而line != null 添加到textBox1

代码:

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

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

    reader.Close();
}

它不起作用,我不知道为什么。我尝试使用using StreamReader,从 URL 下载文件,我可以在下载文件的文件夹中看到。 lastupdate.txt 大小为 1KB。

这是我当前使用MessageBox 的工作代码。如果我删除MessageBox,代码将不起作用。它需要某种等待,否则我不知道:

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");
}

【问题讨论】:

  • textBox1.Text = text ? textBox1.Text += 行?
  • 你确定while被执行并且reader有价值?
  • 你是什么意思? lastupdate.txt 包含数据“1”只是数字...
  • 由于你下载的是Async,剩下的代码基本就跳过了。 if(File.Exists) 将为 false,因为该文件尚不存在或正在被下载线程使用。这就是为什么您的文本框中没有任何内容的原因。您需要设置一个事件处理程序来处理 Ansyc 请求。当您使用 MessageBox 暂停执行代码时,您将允许文件完全下载。
  • 也许尝试while (!reader.EndOfStream),然后分配ReadLine() 值?

标签: c# streamreader readline webclient-download


【解决方案1】:

试试:

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

【讨论】:

    【解决方案2】:

    如果你想要文本框中的文本,阅读所有文本然后将其放入文本框中会更有效:

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

    或:

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

    编辑:

    最新更新后 - 您正在异步下载文件 - 它甚至可能不存在,只是部分存在或在代码执行时处于中间状态。

    如果您只希望文件中的文本字符串不要下载,请改用DownloadString

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

    【讨论】:

    • 如果文件真的很大怎么办?
    • 那么原始版本更糟糕,因为 UI 将被更新请求淹没(即使读取是在后台线程上完成的)。如果它真的很大,阅读文本也应该在后台线程上完成。
    • @wal:如果文件很大,那么文本框包含所有行的问题和问题的想法是错误的
    • 您同意 Akrem @Ravia 真是太好了,不如来点赞他的评论,而不是发表您自己的无用评论。我认为作为免责声明在答案中值得一提,即“如果您的文件不大,那么这个解决方案很好”
    • 如果文件真的很大怎么办?不是1kb
    【解决方案3】:

    试试这个:

    using(StreamReader reader = new StreamReader(Path))
    {
        string line =  reader.ReadLine();
    
        while(line != null)
        {
            textBox1.Text += line;
            line = reader.ReadLine()
        }
    
        reader.Close();
    }
    

    【讨论】:

      【解决方案4】:

      Web Client 有一个相当奇怪的 DownloadFileAsync 方法。返回类型为 void,因此不可等待。另外,这意味着我们甚至没有得到一个任务,所以 ContinueWith 是不可能的。这样我们就可以使用 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 );
      }
      

      我使用了一个可选的异常参数来传递任何异常消息。随意根据需要重构。 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 );
      }
      

      【讨论】:

        【解决方案5】:

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

        textBox1.Text += line;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-12
          • 1970-01-01
          • 1970-01-01
          • 2013-04-20
          相关资源
          最近更新 更多