我相信我们都很熟悉并且可能会使用书籍、在线等提供的大量代码来使用C#读取文件。像这样简单的操作...
StringBuilder fiContents = new StringBuilder();
using (StreamReader fi = new StreamReader(@"C:\a_file.txt"))
{
while (!fi.EndOfStream)
{
fiContents.Append(fi.ReadLine);
}
}
或者只是像这样简短的内容...
using (StreamReader fi = new StreamReader(@"C:\a_file.txt"))
fiContents.Append(fi.ReadToEnd());
现在让我们暂时变成超级赛亚人,做一些非常高级的东西,比如拥有一个
BackgroundWorker
,它将允许我们显示一个加载图像(这是我将使用的),提供一个进程倒计时计时器或ProgressBar
。public void ReadFile(string filename)
{
BackgroundWorker procFile = new BackgroundWorker();
// Progress 1: If we want to show the progress we need to enable the following property
// procFile.WorkerReportsProgress = true;
profile.DoWork += new DoWorkEventHandler((object obj, DoWorkEventArgs ev) =>
{
StringBuilder fiContents = new StringBuilder();
using (StreamReader fi = new StreamReader(filename))
{
while (!fi.EndOfStream)
{
// Progress 2: Report the progress, this will be dealt with by the respective handler (below).
// procFile.ReportProgress((int)(fi.BaseStream.Length / fi.BaseStream.Position) / 100);
fiContents.Append(fi.ReadLine);
}
}
ev.Result = fiContents;
}
/* Progress 3: The handler below will take care of updating the progress of the file as it's processed.
procFile.ProgressChanged += new ProgressChangedEventHandler((object obj, ProgressChangedEventArgs ev) =>
{
// Progress 4: Do something with the value, such as update a ProgressBar.
// ....
}
*/
procFile.RunWorkerCompleted += new RunWorkerCompletedEventHandler((object obj, RunWorkerCompletedEventArgs ev) =>
{
// Do something with the result (ev.Result), bearing in mind, it is a StringBuilder and the ev.Result is an object.
StringBuilder result = ev.Result as StringBuilder;
// ....
}
}
时间到了实际问题...上面是热身之作,用来展示对问题的理解程度,以免遇到这些答案。
我基本上在执行上述最后一个代码示例(即使用BackgroundWorker
)并将读取的内容转储到RichTextBox
中。真的很简单。
然而,我面临的问题是处理大文件(例如 ~222MB)。情况是只需取 .txt 文件,读取它,将通过StringBuilder
构建的结果推送到RichTextBox
中。它无法加载该文件,我得到一个OutOfMemoryException
。一种解决方法是迭代字符串,并从StringBuilder
中添加每个字符(作为char
)。
我始终使用最基本和直接的方法读取文件(如上述示例),但是否有人有任何指导如何改进这一点?如何处理极大的文件等等。
即使是作为讨论的话题,我也欢迎您的想法。
+++++ +++++ +++++ +++++
编辑1(@TaW):当尝试将string
放入RichTextBox
时抛出异常...
FileProcessing.RunWorkerCompleted += new RunWorkerCompletedEventArgs((object obj, RunWorkerCompletedEventArgs e) =>
{
// 'Code' is the RichTextBox in question...
Code.Text = "";
if (e.Result is StringBuilder)
{
Code.Text = (e.Result as StringBuilder).ToString();
}
}
File.ReadAllText(filename)
,但是我很懒。 - user1228