Cambia Research - Supporting the Microsoft .NET Developer Community Supporting the Microsoft .NET Developer Community  

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
The best performance improvement is the transition from the nonworking state to the working state. --John Ousterhout

Share Your Knowledge! -- Create and submit your articles the easy way with WebWriter.

Updated:12:11 AM CT Feb 16, 2007
Posted:12:11 AM CT Feb 16, 2007

How Do I Read a File As an Array of Bytes in C#

Author: Steve Lautenschlager

SnippetIOC#.NET

 Summary

How do I read a file as an array of bytes?
.NET provides a lot of great tools for reading and writing files, lots of stream classes. If you're like me, I kind of find dealing with streams a pain. If I want to read a file I should only have to say "ReadFile" and the content should be there the way I want.

As a result, I tend to write lots of helper methods that hide the stream manipulations so I don't have to remember them. Here's one that will read any file as an array of bytes. I've found this useful with both binary and text files when I didn't have to analyze the data inside--such as a simple file transfer.
public static byte[] GetBytesFromFile(string fullFilePath)
{
	// this method is limited to 2^32 byte files (4.2 GB)

	FileStream fs = 	File.OpenRead(fullFilePath);
	try
	{
		byte[] bytes = new byte[fs.Length];
		fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
		fs.Close();
		return bytes;
	}
	finally
	{
		fs.Close();
	}

}

Add New Comment
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve is the founder and creator of Cambia Research. Developing and maintaining the site combines his passions for technology, writing and education.
Steve holds a Ph.D. in particle physics from Duke University, has worked at CERN, the European center for particle physics (where the web was born) and in Microsoft's web division with microsoft.com, msnbc.com and other web properties. Steve is a web consultant specializing in Microsoft.NET technologies. Read more here.


 
Copyright © Cambia Research 2002-2007. All Rights Reserved. steve [ at ] cambiaresearch.com