Save and Load Memorystream To/From a File

Save and load MemoryStream to/from a file

You may use MemoryStream.WriteTo or Stream.CopyTo (supported in framework version 4.5.2, 4.5.1, 4.5, 4) methods to write content of memory stream to another stream.

memoryStream.WriteTo(fileStream);

Update:

fileStream.CopyTo(memoryStream);
memoryStream.CopyTo(fileStream);

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 bytes to the steam, it doesn't override existing bytes. But then to read it (for copy purposes) you need to set the position to the start so you can start reading at the start.

C# write memorystream to file

you don't need any StreamReader, just do it like this:

public void WriteToFile(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);

using(var fs = new FileStream("/path/to/file", FileMode.OpenOrCreate))
{
stream.CopyTo(fs);
}
}

//var memoryStream...
//...

WriteFoFile(memoryStream);

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.

how to load a file into memory stream

You don't need to load a file into a MemoryStream.

You can simply call File.OpenRead to get a FileStream containing the file.

If you really want the file to be in a MemoryStream, you can call CopyTo to copy the FileStream to a MemoryStream.

MemoryStream output to a file c#

My problem is in the else body

Well you're handling that in a different way to in the first if body.

In the first if body, you're explicitly flushing the writer and rewinding the stream:

sw.Flush();
stream.Position = 0;

You're not doing either of those in the else body, so you won't get any data that's already been written to the stream (no rewind) and there could still be data buffered in the StreamWriter (no flush). That's one problem.

Next, you're checking your "limit" without flushing the StreamWriter, which means there could be a bunch more data meaning you should compress, but you're not. So I suggest you call sw.Flush() before your if statement occurs at all.

Finally, I'd strongly recommend against creating another byte array for no reason - the body of your final using statement can just be:

stream.CopyTo(file);

c# store files content into MemoryStream and read back

Warning: Reading undefined amount of files with undefined total size can cause OutOfMemoryException. Be careful with this.

Btw, if you want to store the data in the memory, it's better to store it in arrays.

public static Dictionary<int, byte[]> Data { get; private set; }

public static void LoadAllTemplates()
{
Data = new Dictionary<int, byte[]>();
DirectoryInfo dir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates"));

foreach (FileInfo fileInfo in dir.GetFiles("*.xml"))
{
if (int.TryParse(fileInfo.Name.Remove(fileInfo.Name.Length - fileInfo.Extension.Length), out int key))
{
Data[key] = File.ReadAllBytes(fileInfo.FullName);
Console.WriteLine($"File {fileInfo.Name} {fileInfo.Length / 1024} kB size added to Data");
}
else
Console.WriteLine($"Failed to parse filename {fileInfo.Name}");
}
}

Usage could be

StreamReportFiles.LoadAllTemplates();
Console.WriteLine(Encoding.UTF8.GetString(StreamReportFiles.Data[10]));

How to download memorystream to a file?

At the point in your code where you copy the data to an array, the TextWriter might not have flushed the data. This will happen when you Flush() or when you Close() it.

See if this works:

MemoryStream memoryStream = new MemoryStream();
TextWriter textWriter = new StreamWriter(memoryStream);
textWriter.WriteLine("Something");
textWriter.Flush(); // added this line
byte[] bytesInStream = memoryStream.ToArray(); // simpler way of converting to array
memoryStream.Close();

Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=name_you_file.xls");
Response.BinaryWrite(bytesInStream);
Response.End();

After fileStream.CopyTo(memoryStream), memoryStream is null

Stream.CopyTo copies from the current position of fileStream which has been changed by SaveJpeg() so you need to reset it;

var memoryStream = new MemoryStream();

fileStream.Position = 0;
fileStream.CopyTo(memoryStream);


Related Topics



Leave a reply



Submit