locked
Read 3GB files RRS feed

  • Question

  • User1610800555 posted

    i am getting error (out of memory exception) when i read large files(3GB)

    this is my code

                        Dim fs As System.IO.FileStream
                        fs = File.Open(fpath, FileMode.Open, FileAccess.Read, FileShare.None)
                        Dim filelen As Long = fs.Length
                        Dim buffer(fs.Length) As Byte
                        fs.Read(buffer, 0, filelen)
                        fs.Close()



    Saturday, April 27, 2013 5:33 AM

Answers

  • User1508394307 posted

    You read the entire file into memory which seems too much to your server.

    Try to use buffering. 

    Dim oFile As System.IO.FileInfo
    oFile = New System.IO.FileInfo(sFilePath)
    
    oFileStream = oFile.OpenRead()
    
    Dim fileData As Byte() = New Byte(255) {}
    ' buffer
    Dim lBytes As Integer = oFileStream.Read(fileData, 0, fileData.Length)
    
    While lBytes <> 0
    	oNewFileStream.Write(fileData, 0, lBytes)
    	lBytes = oFileStream.Read(fileData, 0, fileData.Length)
    End While
    
    oFileStream.Close()
    oNewFileStream.Close()

    If you you want to send the contents of a file out to an ASPNET response stream

    Using fs = New FileStream(fpath, FileMode.Open, FileAccess.Read)
    	Response.BufferOutput = False
    	' to prevent buffering
    	Dim buffer As Byte() = New Byte(1023) {}
    	Dim bytesRead As Integer = 0
    	While (InlineAssignHelper(bytesRead, fs.Read(buffer, 0, buffer.Length))) > 0
    		Response.OutputStream.Write(buffer, 0, bytesRead)
    	End While
    End Using

    Hope this helps.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 27, 2013 6:34 AM