内存不足异常读写文本文件 [英] Out of memory exception reading and writing text file

查看:107
本文介绍了内存不足异常读写文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下代码几秒钟后,出现内存不足异常.在引发异常之前,它不会编写任何内容.文本文件的大小约为半GB.我也正在写的文本文件最终将约为3/4 GB.是否有任何技巧可以绕过此异常?我认为是因为文本文件太大.

I get an out of memory exception a few seconds after I execute the following code. It doesn't write anything before the exception is thrown. The text file is about half a gigabyte in size. The text file I'm writing too will end up being about 3/4 of a gigabyte. Are there any tricks to navigate around this exception? I assume it's because the text file is too large.

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

我已将代码更改为以下代码,但仍然得到相同的提示?

I have changed my code to the following yet I still get the same excpetion?

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来处理流.这样可以确保在出现异常情况下关闭文件.

Read the file line by line, it will help you to avoid OutOfMemoryException. And I personnaly prefer using using's to handle streams. It makes sure that the file is closed in case of an exception.

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

这篇关于内存不足异常读写文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆