use*_*907 7 c# readline streamreader webclient-download
我在使用StreamReader和line != null添加时读取文件时遇到问题textBox1
码:
using(StreamReader reader = new StreamReader("lastupdate.txt"))
{
string line;
while((line = reader.ReadLine()) != null)
{
textBox1.Text = line;
}
reader.Close();
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,我不知道为什么.我尝试使用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");
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*ana 13
试试:
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("lastupdate.txt"))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
textbox.Text = sb.Tostring();
Run Code Online (Sandbox Code Playgroud)
如果您想要文本框中的文本,那么阅读所有文本然后将其放入文本框会更有效:
var lines = File.ReadAllLines("lastupdate.txt");
textBox1.Lines = lines; //assuming multi-line text box
Run Code Online (Sandbox Code Playgroud)
要么:
textBox1.Text = File.ReadAllText("lastupdate.txt");
Run Code Online (Sandbox Code Playgroud)
编辑:
在最新更新之后 - 您正在异步下载文件- 它甚至可能不在那里,只是部分存在或在代码执行时处于中间状态.
如果您只想让文件中的文本字符串不下载,请DownloadString改用:
string text = "";
using (WebClient wc = new WebClient())
{
text = wc.DownloadString(new Uri(Settings.Default.patchCheck));
}
textBox1.Text = text;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83960 次 |
| 最近记录: |