convert string to memory stream – Memory stream is not expandable?

The following code works correctly for me public class Foo { public static void Main() { var myPage = “test string”; var repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(myPage)); } } It seems that the correct way to do this is to create the MemoryStream using the default constructor var repo = new System.IO.MemoryStream(); and then write to … Read more

Attach a file from MemoryStream to a MailMessage in C#

Here is the sample code. System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(ms); writer.Write(“Hello its my sample file”); writer.Flush(); writer.Dispose(); ms.Position = 0; System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct); attach.ContentDisposition.FileName = “myFile.txt”; // I guess you know how to send email with an attachment // after sending email … Read more

Writing to MemoryStream with StreamWriter returns empty

You are forgetting to flush your StreamWriter instance. public static Stream Foo() { var memStream = new MemoryStream(); var streamWriter = new StreamWriter(memStream); for (int i = 0; i < 6; i++) streamWriter.WriteLine(“TEST”); streamWriter.Flush(); <– need this memStream.Seek(0, SeekOrigin.Begin); return memStream; } Also note that StreamWriter is supposed to be disposed of, since it implements … Read more

Copy MemoryStream to FileStream and save the file?

You need to reset the position of the stream before copying. outStream.Position = 0; outStream.CopyTo(fileStream); You used the outStream when saving the file using the imageFactory. That function populated the outStream. While populating the outStream the position is set to the end of the populated area. That is so that when you keep on writing … Read more

Serializing/deserializing with memory stream

This code works for me: public void Run() { Dog myDog = new Dog(); myDog.Name= “Foo”; myDog.Color = DogColor.Brown; System.Console.WriteLine(“{0}”, myDog.ToString()); MemoryStream stream = SerializeToStream(myDog); Dog newDog = (Dog)DeserializeFromStream(stream); System.Console.WriteLine(“{0}”, newDog.ToString()); } Where the types are like this: [Serializable] public enum DogColor { Brown, Black, Mottled } [Serializable] public class Dog { public String Name … Read more

Reading from memory stream to string

If you’d checked the results of stream.Read, you’d have seen that it hadn’t read anything – because you haven’t rewound the stream. (You could do this with stream.Position = 0;.) However, it’s easier to just call ToArray: settingsString = LocalEncoding.GetString(stream.ToArray()); (You’ll need to change the type of stream from Stream to MemoryStream, but that’s okay … Read more