Let's Talk About .NET, Java, and Various File Formats!

Reading a file from the disk into the MemoryStream is a very common requirement while working with files in your .NET applications. It is important to read the files to MemoryStream when you want to process the file inside memory. For example, when you want to render a file from the server to the browser. This is very simple and you can use the following code snippet to read the file contents from the disk to the MemoryStream.

C# Code Snippet:

//open file from the disk (file path is the path to the file to be opened)
using (FileStream fileStream = File.OpenRead(filePath))
{
//create new MemoryStream object
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
//read file to MemoryStream
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
}

VB.NET Code Snippet:

‘open file from the disk (file path is the path to the file to be opened)
Using fileStream As FileStream = File.OpenRead(filePath)
‘create new MemoryStream object
Dim memStream As New MemoryStream()
memStream.SetLength(fileStream.Length)
‘read file to MemoryStream
fileStream.Read(memStream.GetBuffer(), 0, CInt(Fix(fileStream.Length)))
End Using

Advertisements

Comments on: "Read File from Disk into MemoryStream using C# or VB.NET" (1)

  1. (int)fileStream.Length is not suitable for large files (more than 2Gb)
    even thought files with that size should be lazy-loaded in a background thread

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: