// Create a new MemoryStream MemoryStream ms = new MemoryStream(); // Write some data to the stream byte[] data = Encoding.UTF8.GetBytes("Hello World"); ms.Write(data, 0, data.Length); // Close the stream ms.Close();
// Create a new FileStream and StreamReader to read a file using (FileStream fs = new FileStream("example.txt", FileMode.Open)) using (StreamReader reader = new StreamReader(fs)) { // Read the contents of the file into a MemoryStream MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(reader.ReadToEnd())); // Close the MemoryStream ms.Close(); }In this example, we read the contents of a file into a MemoryStream. After we have finished working with the MemoryStream, we call the Close method to release any resources associated with it. The System.IO namespace is included in the .NET Framework, so it is part of the standard library that is available to any C# program.