![](/img/trans.png)
[英]C#: Using StreamReader to read line from txt file, but Peek() return -1 even there are a lot of lines left
[英]C# read line from file with StreamReader with DownloadFileAsync
我在使用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");
}
试试:
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("lastupdate.txt"))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
textbox.Text = sb.Tostring();
如果您想要文本框中的文本,那么阅读所有文本然后将其放入文本框会更有效:
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;
试试这个 :
using(StreamReader reader = new StreamReader(Path))
{
string line = reader.ReadLine();
while(line != null)
{
textBox1.Text += line;
line = reader.ReadLine()
}
reader.Close();
}
Web客户端有一个相当离奇的DownloadFileAsync方法。 返回类型无效,因此无法等待。 此外,这意味着我们甚至没有得到任务,所以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 );
}
上面给出的答案是正确的,但在你的代码中,只需更改1行:
textBox1.Text += line;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.