Wednesday, October 26, 2011

FileStream and MemoryStream Conversions

Once upon a time, I was had some code like the following:

using (FileStream destStream = new FileStream(writePath, FileMode.Create))
{
 /* 3rd party lib writes to destStream */
}

Trouble was... the 3rd party call had the potential to throw an error. Of course, by then, the file at "writePath" had already been created. This was no good.

Lucky for me, the 3rd party call didn't require a FileStream for writing -- any old Stream implementation would work. So why not a MemoryStream? This way, if the write fails, all I've lost is some to-be-garbage-collected memory.

The following methods helped me move my data between FileStream and MemoryStream objects:

public static MemoryStream ReadFileToMemoryStream(string filePath)
{
 MemoryStream memStream = new MemoryStream();
 using (FileStream fileStream = File.OpenRead(filePath))
 {
  memStream.SetLength(fileStream.Length);
  fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
 }
 return memStream;
}

public static void WriteMemoryStreamToFile(MemoryStream memoryStream, string filePath)
{
 WriteMemoryStreamToFile(memoryStream, filePath, FileMode.Create);
}

public static void WriteMemoryStreamToFile(MemoryStream memoryStream, string filePath, FileMode fileMode)
{
 WriteMemoryStreamToFile(memoryStream, filePath, FileMode.Create, FileAccess.Write);
}

public static void WriteMemoryStreamToFile(MemoryStream memoryStream, string filePath, FileMode fileMode, FileAccess fileAccess)
{
 using (var fileStream = new FileStream(filePath, fileMode, fileAccess))
 {
  byte[] data = memoryStream.ToArray();
  fileStream.Write(data, 0, data.Length);
 }
}

No comments:

Post a Comment