简体   繁体   中英

How to write big files with BinaryWriter

I have some program which write a large binary files. And I meet the problem: sometimes my programm crash on file writing without throwing any error (block catch don't execute. I write some test console application to find and fix this problem. Somthing like this:

static void Main(string[] args)
{
    for (int j = 0; j < 100; j++)
    {
        string fileName = @"D:\Users\nimci\Desktop\buf\"+j+".bin";
        using (var output =
            new BinaryWriter(File.Open(fileName, FileMode.Create, FileAccess.Write)))
        {
            for (int i = 0; i < 4000000; i++)
            {
                output.Write(i);
                //if(i%1000==0)   Thread.Sleep(1);
            }
        }
    }
}

And i have such results: Some files have 0 size. For example the files with numbers 8, 10, 15, 17,...

On my home (less powerfull) computer all the files have been written correctly, byt on my work computer some of them have 0 size. If I uncomment Thread.Sleep(1); (or slow my program in other way) all the files correct on my work computer too, but such "fix" don't work on my server computer. Can anybody explain what the error occured and how can I fix it? I try to use try-cath-finally instead using, but catch block don't catch this error.

Try adding Flush:

        for (int i = 0; i < 4000000; i++)         
        {         
            output.Write(i);         
            //if(i%1000==0)   Thread.Sleep(1);         
        }  
        output.Flush(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM