O'Reilly Forums: Filestreaming System.outofmemoryexception - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Filestreaming System.outofmemoryexception Filestreaming getting System.OutofmemoryException

#1 User is offline   sharonc 

  • New Member
  • Pip
  • Group: Members
  • Posts: 1
  • Joined: 08-March 12

Posted 08 March 2012 - 07:27 AM

i,
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);
rdr.Close();
fs.Close();

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

machine.

thanks for your help.

Sharon

Attached File(s)


0

#2 User is offline   Sikta_26785 

  • Active Member
  • PipPipPip
  • Group: Members
  • Posts: 68
  • Joined: 18-May 11

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)
        {
            fileData.Add(rdr.ReadByte());
        }
     }
}

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users