Greg
Greg

Reputation: 441

Large file and OutOfMemoryException

I’m new to C# and my boss wants me to investigate an OutOfMemory exception. The code that throws the exception is below specifically the first line if the file is large (>50MB):

     byte[] fileBytes = ws.getFile(f.FileId, f.Version); // This line gets the file from a webservice.
     File.WriteAllBytes(Path.Combine(folder, f.FileId.ToString("0")), fileBytes);

I’ve read somewhere that using byte[] is not a good idea for large files. can some help please ?

Upvotes: 1

Views: 1718

Answers (1)

machine
machine

Reputation: 1390

Currently, your code is downloading the entire file and sticking it on the heap, then writing to a file locally.

To avoid the OutOfMemoryException, you will want to write to the disk as you go instead of waiting until the end. You can achieve this by getting the file from the webservice as a stream, opening a new file stream for writing and copying the contents over.

Upvotes: 3

Related Questions