File Operations with MemoryStream: Saving and Loading
In situations where you need to serialize a data structure into a memory stream, saving and loading the serialized structure becomes necessary. Here's how you can achieve this:
Saving a MemoryStream to a File
To save the contents of a memory stream to a file, you can employ the MemoryStream.WriteTo method or use Stream.CopyTo.
Using MemoryStream.WriteTo:
<code class="c#">using (FileStream fileStream = new FileStream("serializedStructure.bin", FileMode.Create)) { memoryStream.WriteTo(fileStream); }</code>
Using Stream.CopyTo:
.NET 4.5.2 and Later
<code class="c#">using (FileStream fileStream = new FileStream("serializedStructure.bin", FileMode.Create)) { fileStream.CopyTo(memoryStream); }</code>
.NET 4.5 and Earlier
<code class="c#">using (FileStream fileStream = new FileStream("serializedStructure.bin", FileMode.Create)) { memoryStream.CopyTo(fileStream); }</code>
Loading a MemoryStream from a File
To load the contents of a file into a memory stream, you can also utilize the MemoryStream.WriteTo or Stream.CopyTo methods.
Using MemoryStream.WriteTo:
<code class="c#">using (FileStream fileStream = new FileStream("serializedStructure.bin", FileMode.Open)) { fileStream.CopyTo(memoryStream); }</code>
Using Stream.CopyTo:
.NET 4.5.2 and Later
<code class="c#">using (FileStream fileStream = new FileStream("serializedStructure.bin", FileMode.Open)) { memoryStream.CopyTo(fileStream); }</code>
.NET 4.5 and Earlier
<code class="c#">using (FileStream fileStream = new FileStream("serializedStructure.bin", FileMode.Open)) { fileStream.CopyTo(memoryStream); }</code>
By following these steps, you can effectively save and load a memory stream to or from a file.
The above is the detailed content of How do I save and load a MemoryStream to and from a file?. For more information, please follow other related articles on the PHP Chinese website!