Exception from reading and writing text file memory

I get a memory exception a few seconds after the following code is executed. He writes nothing before an exception is thrown. The text file is about half a gigabyte in size. The text file I'm writing will also be about 3/4 gigabytes. Are there any tricks to navigate this exception? I guess this is because the text file is too big.

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 changed my code to the following, but still getting the same expiment?

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();
}
+4
source share
3 answers

, OutOfMemoryException. using . , .

public static void ToCSV(string fileWRITE, string fileREAD)
{
    usint(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();
        }
    } 
}
+1

. #

, . .

+1

, , . , . , , .

, , . , .

+1

Source: https://habr.com/ru/post/1538679/


All Articles