Writing a memory stream to a file

write memorystream to file c#
write memorystream to excel file c#
memorystream to pdf c#
c# save memorystream to image file
memorystream c#
save memorystream to excel file c#
download excel file from memorystream c#
c# memorystream to string

I have tried retrieving data in the json format as a string and writing it to a file and it worked great. Now I am trying to use MemoryStream to do the same thing but nothing gets written to a file - merely [{},{},{},{},{}] without any actual data.

My question is - how can I check if data indeed goes to memory stream correctly or if the problem occurs somewhere else. I do know that myList does contain data.

Here is my code:

MemoryStream ms = new MemoryStream();
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<myClass>));
dcjs.WriteObject(ms, myList);

using (FileStream fs = new FileStream(Path.Combine(Application.StartupPath,"MyFile.json"), FileMode.OpenOrCreate))
{
                ms.Position = 0;
                ms.Read(ms.ToArray(), 0, (int)ms.Length);
                fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
                ms.Close();
                fs.Flush();
                fs.Close();
 }

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.

Writing a memory stream to a file, There is a very handy method, Stream.CopyTo(Stream) . using (MemoryStream ms = new MemoryStream()) { StreamWriter writer = new  Writes the sequence of bytes contained in source into the current memory stream and advances the current position within this memory stream by the number of bytes written. Write(Byte[], Int32, Int32) Writes a block of bytes to the current stream using data read from a buffer.

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; }
}

How to Save the MemoryStream as a file in c# and VB.Net, Save MemoryStream to a String​​ StreamWriter sw = new StreamWriter(memoryStream); sw. WriteLine("Your string to Memoery"); This string is currently saved in the StreamWriters buffer. Flushing the stream will force the string whose backing store is memory (MemoryStream). Actually, it represents a pure, in-memory stream of data. Memory is much faster when compared to disk or network accesses. The following section explains : # MemoryStream to File # MemoryStream to String MemoryStream to FileStream. With MemoryStream, you can act upon the byte[] stored in memory rather than a file or other resource.

This line looks problematic:

ms.Read(ms.ToArray(), 0, (int)ms.Length);

You shouldn't need to read anything into the memory stream at this point, particularly when you're code is written to read ms into ms.

I'm pretty confident that simply removing this line will fix your problem.

MemoryStream.Write Method (System.IO), Writes the sequence of bytes contained in source into the current memory stream and advances the current position within this memory stream by the number of  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 bytes to the steam, it doesn't override existing bytes.

//reset the position of the stream

ms.Position = 0;

//Then copy to filestream

ms.CopyTo(fileStream);

MemoryStream Class (System.IO), The following code example shows how to read and write data using memory as If a MemoryStream object is added to a ResX file or a .resources file, call the  Note that in this example, the input stream has known and pre-determined data – such as a file on disk or an in-memory stream. Because of this, we don't need to do any bounds checking and we can – if memory allows – simply read it and write it in one go. If the input stream is linked to an ongoing stream

 using (var memoryStream = new MemoryStream())
 {
    ...

     var fileName = $"FileName.xlsx";
     string tempFilePath = Path.Combine(Path.GetTempPath() + fileName );
     using (var fs = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
     {
        memoryStream.WriteTo(fs);
     }

 }

MemoryStream output to a file c#, string fileName = GetFileName(); using (var stream = new MemoryStream()) I try to write all the content of memory stream into a plain text file when no need to​  Writes the sequence of bytes contained in source into the current memory stream and advances the current position within this memory stream by the number of bytes written. Write(ReadOnlySpan<Byte>) When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

Save the MemoryStream as a file : MemoryStream « File Directory , IO; class MainClass { public static void SaveMemoryStream(MemoryStream ms, string FileName) { FileStream outStream = File.OpenWrite(FileName); ms. setting the memory streams position to the beginning might help. stream.Position = 0; But the core problem is that the StreamWriter is closing your memory stream when it is closed. Simply flushing that stream where you end the using block for it and only disposing of it fter you have read the data out of the memory stream will solve this for you.

Convert MemoryStream into FileStream, Sometimes, we need to convert FileStream into MemoryStream. convert memoryStream into fileStream because filestream is able to save to disk file. into one single byte array, and then write byte array into Target_Stream. Writing text to a file by using a stream (4 steps) First, open the file by calling the StorageFile.OpenAsync method. It returns a stream of the file's content when the open operation completes. var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

C# write text files - File, StreamWriter, FileStream, For instance, MemoryStream works with data located in the memory and FileStream with data in a files. C# write text file with File.WriteAllText. The  that, to provide a stream interface onto a block of memory. The FileStream writes to files, and so it makes sense to use a FileStream to dump out the internal buffer of the MemoryStream (which is what GetBuffer() provides) to a file.--John Wood EMail: first name, dot, last name, at priorganize.com

Comments
  • Not saying that this will fix your problem, but consider cleaning up the code by using Stream.CopyTo Method.
  • ms.Read(ms.ToArray(), 0, (int)ms.Length); Why are you reading the memory stream, overwriting whatever was put in there by dcjs.WriteObject? That seems like your problem there, don't reset the stream position and write over itself.
  • Why are you writing to the MemoryStream before the FileStream? But with .net 4.0 you should have access to Stream.CopyTo(Stream).
  • I tried ms.CopyTo(fs) but gotten same result
  • @ElenaDBA The problem isn't your file writing. The problem is in your Serializer.
  • Nothing happened at all - the file was unchanged
  • I updated the code with a modification, you need to use Seek(0, SeekOrigin.Begin)
  • I'm using .Net Framework 3.5, so that may have something to do with it, but I could use Stream.CopyTo(Stream) as it did not exist. Instead, I had to use Stream.WriteTo(Stream).
  • Instead of ms.Seek(0, SeekOrigin.Begin) you can use ms.Position = 0 to "rewind" the stream
  • Before I tried ms.WriteTo(fs) but result was the same
  • There is no reason to reset the stream position, just calling ms.ToArray() will copy the entire memory stream (beginning at zero) to an array. From the documentation "Writes the stream contents to a byte array, regardless of the Position property."