gpt4 book ai didi

c# - 高级文件读取

转载 作者:太空狗 更新时间:2023-10-29 21:54:07 25 4
gpt4 key购买 nike

我相信我们都很熟悉,并且可能会使用书籍、在线等提供的大量代码来使用 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());

现在让我们来看看 super 赛亚人,做一些非常奇特的事情,比如拥有一个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 .解决这个问题的一种方法是遍历字符串并从文件 char 添加每个字符(作为 StringBuilder ),这需要相当多的时间(并且仍然不加载文件)。 .

我一直使用最基本和最直接的方式来读取文件(例如上面给出的示例),但是有人对如何改进这一点有任何指导吗?处理超大文件的方法?等等

即使作为讨论文章,我也欢迎您的想法。

++++++++++++++++++++

编辑 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();
}
}

最佳答案

是否有限制要求您使用 RichTextBox 作为控件来显示您的内容?此控件未虚拟化,会导致性能(以及内存错误的外观)问题。

有一个家庭document viewing controls更适合显示大型文档。根据您的需要存在各种控件(固定、通过页面流动或滚动)。此外,您还可以获得搜索、打印、缩放和一些通常对查看大型文档有用的其他功能。

关于c# - 高级文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23198564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com