1 Attachment(s)
Filestream System.OutofmemoryException
Hi,
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
Re: Filestream System.OutofmemoryException
You're trying to read 521MB directly into memory... and apparently there is not enough. That seems pretty evident. When reading large files you should use the stream as a... well, as a stream, not a big huge block of data.
Re: Filestream System.OutofmemoryException
BigEd,
I'm new to C#, any ideas how I can fix this?
Sharon
Re: Filestream System.OutofmemoryException
Don't call ReadBytes. At least, don't pass in the entire size of the file. That reads the whole thing in. Instead, use something like ReadByte and iterate over the stream, letting the library take care of buffering chunks of it into memory for you.
Re: Filestream System.OutofmemoryException
Hi,
As I mentioned I have a machine that has 8 GB of memory. I had to shut down my machine to take it home last night.
When I tried to load the file again today it loaded with no problem. Normally I will only be loading one file at a
time, but in this case I was testing my Development database and was loading 28 files one right after the other.
Now my question is, since it is working ok now, is there a problem I still need to fix?
Sharon
Re: Filestream System.OutofmemoryException
No, it does not mean it will always work, but on an x64 machine with 8GB of RAM (assuming that your C# app is targeting x64 or Any CPU) it would be fine most of the time. You should try to avoid it if possible, but if your test machine represents normal operating conditions you should be ok.