Jump to content


Filestreaming System.outofmemoryexception

  • Please log in to reply
1 reply to this topic

#1 sharonc


    New Member

  • Members
  • Pip
  • 1 posts

Posted 08 March 2012 - 07:27 AM

I am getting an System.OutofmemoryException when using Filestream to load zip file. the file is 521MB. My code is:

//Insert using Filestream, file into SQL Server Table
private void btnInsert_Click(object sender, EventArgs e)
OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.InitialDirectory = Directory.GetCurrentDirectory();
if (openFileDlg.ShowDialog() == DialogResult.OK)
FileInfo fi = new FileInfo(openFileDlg.FileName);
FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
BinaryReader rdr = new BinaryReader(fs);
byte[] fileData = rdr.ReadBytes((int)fs.Length);

My program dies on this line: byte[] fileData = rdr.ReadBytes((int)fs.Length);
i have also attached the detail for the System.OutofMemoryException. I am runing this on a Windows 7, 64bit


thanks for your help.


Attached Files

#2 Sikta_26785


    Active Member

  • Members
  • PipPipPip
  • 68 posts

Posted 08 March 2012 - 05:40 PM

The length of the file is causing the byte[] declaration to attempt to allocate more memory than is available. I would recommend not trying to process the entire file at once but rather in chunks or try using a List<byte> instead. Google "C# reading large files" and you should see there a lot of different options available.

Also, I recommend a using statement when working with disposable objects to ensure they are disposed of when you are done using them. If you had an exception while the stream or reader were open and it skipped the close calls, these resources wouldn't be properly disposed of.

List<byte> fileData = new List<byte>();
using (FileStream fs = new FileStream(fi.FUllName, FileMode.Open, FileAccess.Read))
    using (BinaryReader rdr = new BinaryReader(fs))
        int length = rdr.BaseStream.Length;
        while (rdr.BaseStream.Position < length)

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users