【发布时间】: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