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

Posts tagged ‘.NET’

Read File from Disk into MemoryStream using C# or VB.NET

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

Verify .NET Assembly for Type-Safe Code

Some times, developers need to produce the CIL in such a way that it meets type safety requirements. This type-safe code can only be generated by avoiding certain language constructs. In order to make sure that the .NET assembly contains type-safe code, you need to verify the assembly. The assembly can be verified using PEVerify utility from Microsoft.

If you have installed Visual Studio on your computer, this utility (peverify.exe) will already be there. It provides various options, however the simplest way to verify the assembly is to use peverify.exe along with the assembly path/name.

It will take a while and show you the result. If the assembly contains type-safe code, the following message will be shown on the command window: All Classes and Methods in <assembly path/name> Verified.