Writing a memory stream to a file
There is a very handy method, Stream.CopyTo(Stream)
.
using (MemoryStream ms = new MemoryStream()){ StreamWriter writer = new StreamWriter(ms); writer.WriteLine("asdasdasasdfasdasd"); writer.Flush(); //You have to rewind the MemoryStream before copying ms.Seek(0, SeekOrigin.Begin); using (FileStream fs = new FileStream("output.txt", FileMode.OpenOrCreate)) { ms.CopyTo(fs); fs.Flush(); }}
Also, you don't have to close fs
since it's in a using statement and will be disposed at the end.
//reset the position of the stream
ms.Position = 0;
//Then copy to filestream
ms.CopyTo(fileStream);
The issue is nothing to do with your file stream/ memory stream. The problem is that DataContractJsonSerializer
is an OPT IN Serializer. You need to add [DataMemberAttribute]
to all the properties that you need to serialize on myClass
.
[DataContract]public class myClass{ [DataMember] public string Foo { get; set; }}