MemoryStream in C#
By Mash B
The most common use of a MemoryStream is to store temporarily data that will be
written to a file eventually. Using a MemoryStream, you can take your time to create the
stream in memory, add data to it, and then write it all to disk at once—minimizing the
time the file needs to be locked open.
// Create a MemoryStream object
using(MemoryStream ms = new MemoryStream())
{
// writing strings to the MemoryStream
using(StreamWriter sw = new StreamWriter(ms)) // Avoiding file to be locked by using memorystream instead of file name
{
// Write to the StreamWriter and MemoryStream
sw.WriteLine("Hello, World!");
// Flush the contents of the StreamWriter so it can be written to disk
sw.Flush();
// Write the contents of the MemoryStream to a file
ms.WriteTo(File.Create("memory.txt"));
}
}
MemoryStream in C# (2443 Views)