Home >Backend Development >C++ >How do I save and load a MemoryStream to and from a file?

How do I save and load a MemoryStream to and from a file?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 11:08:29729browse

How do I save and load a MemoryStream to and from a file?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn