gpt4 book ai didi

c# - Out of memory异常读写文本文件

转载 作者:太空狗 更新时间:2023-10-30 01:36:04 25 4
gpt4 key购买 nike

我在执行以下代码几秒钟后遇到内存不足异常。在抛出异常之前它不写任何东西。该文本文件的大小约为 0.5 GB。我正在编写的文本文件最终也将是大约 3/4 千兆字节。有什么技巧可以绕过这个异常吗?我认为这是因为文本文件太大。

public static void ToCSV(string fileWRITE, string fileREAD)
{
StreamWriter commas = new StreamWriter(fileWRITE);
var readfile = File.ReadAllLines(fileREAD);


foreach (string y in readfile)
{

string q = (y.Substring(0,15)+","+y.Substring(15,1)+","+y.Substring(16,6)+","+y.Substring(22,6)+ ",NULL,NULL,NULL,NULL");
commas.WriteLine(q);
}

commas.Close();
}

我已将我的代码更改为以下内容,但我仍然得到相同的异常?

public static void ToCSV(string fileWRITE, string fileREAD)
{
StreamWriter commas = new StreamWriter(fileWRITE);

using (FileStream fs = File.Open(fileREAD, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
string y;
while ((y = sr.ReadLine()) != null)
{
string q = (y.Substring(0, 15) + "," + y.Substring(15, 1) + "," + y.Substring(16, 6) + "," + y.Substring(22, 6) + ",NULL,NULL,NULL,NULL");
commas.WriteLine(q);
}
}

commas.Close();
}

最佳答案

逐行读取文件,这将帮助您避免OutOfMemoryException。我个人更喜欢使用 using 来处理流。它确保在出现异常时关闭文件。

public static void ToCSV(string fileWRITE, string fileREAD)
{
using(var commas = new StreamWriter(fileWRITE))
using(var file = new StreamReader("yourFile.txt"))
{
var line = file.ReadLine();

while( line != null )
{
string q = (y.Substring(0,15)+","+y.Substring(15,1)+","+y.Substring(16,6)+","+y.Substring(22,6)+ ",NULL,NULL,NULL,NULL");
commas.WriteLine(q);
line = file.ReadLine();
}
}
}

关于c# - Out of memory异常读写文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23381474/

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