IT-Swarm.Net

将MemoryStream保存并加载到文件中

我正在将结构序列化为MemoryStream,我想保存并加载序列化结构。

那么,如何将MemoryStream保存到文件中并将其从文件中加载回来?

233
Mahdi Ghiasi

您可以使用MemoryStream.WriteToStream.CopyTo(在框架版本4.5.2,4.5.1,4.5,4中支持)方法将内存流的内容写入另一个流。

memoryStream.WriteTo(fileStream);

更新:

fileStream.CopyTo(memoryStream);
memoryStream.CopyTo(fileStream);
318
adatapost

假设MemoryStream名称是ms

此代码将MemoryStream写入文件:

using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write)) {
   byte[] bytes = new byte[ms.Length];
   ms.Read(bytes, 0, (int)ms.Length);
   file.Write(bytes, 0, bytes.Length);
   ms.Close();
}

这会将文件读入MemoryStream:

using (MemoryStream ms = new MemoryStream())
using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) {
   byte[] bytes = new byte[file.Length];
   file.Read(bytes, 0, (int)file.Length);
   ms.Write(bytes, 0, (int)file.Length);
}

在.Net Framework 4+中,您可以简单地将FileStream复制到MemoryStream,并且反向就像这样简单:

MemoryStream ms = new MemoryStream();
using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read))
    file.CopyTo(ms);

和Reverse(MemoryStream到FileStream):

using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write))
    ms.CopyTo(file);
228
Ashkan Mobayen Khiabani

即使存在异常(很可能是文件I/O),流也应该被处理掉 - 使用子句是我最喜欢的方法,所以对于编写MemoryStream,你可以使用:

using (FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write)) {
    memoryStream.WriteTo(file);
}

阅读它:

using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) {
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);
    ms.Write(bytes, 0, (int)file.Length);
}

如果文件很大,那么值得注意的是,读取操作将使用两倍于总文件大小的内存 。一种解决方案是从字节数组创建MemoryStream - 以下代码假定您不会写入该流。

MemoryStream ms = new MemoryStream(bytes, writable: false);

我的研究(如下)显示内部缓冲区与传递它的字节数组相同,因此它应该节省内存。

byte[] testData = new byte[] { 104, 105, 121, 97 };
var ms = new MemoryStream(testData, 0, 4, false, true);
Assert.AreSame(testData, ms.GetBuffer());
58
Rob Church

对于任何寻找短版本的人:

var memoryStream = new MemoryStream(File.ReadAllBytes("1.dat"));

File.WriteAllBytes("1.dat", memoryStream.ToArray()); 
31
Slai

写入文件的组合答案可以是;

MemoryStream ms = new MemoryStream();    
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
18
Berkay Turancı

对于加载文件,我更喜欢这个

MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(file))
{
    fs.CopyTo(ms);
}
14
ProVega

保存到文件中

Car car = new Car();
car.Name = "Some fancy car";
MemoryStream stream = Serializer.SerializeToStream(car);
System.IO.File.WriteAllBytes(fileName, stream.ToArray());

从文件加载

using (var stream = new MemoryStream(System.IO.File.ReadAllBytes(fileName)))
{
    Car car = (Car)Serializer.DeserializeFromStream(stream);
}

哪里

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialization
{
    public class Serializer
    {
        public static MemoryStream SerializeToStream(object o)
        {
            MemoryStream stream = new MemoryStream();
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, o);
            return stream;
        }

        public static object DeserializeFromStream(MemoryStream stream)
        {
            IFormatter formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            object o = formatter.Deserialize(stream);
            return o;
        }
    }
}

最初这个类的实现已发布 这里

[Serializable]
public class Car
{
    public string Name;
}
13
Vadim Gremyachev

我使用Panel Control添加图像甚至流视频,但您可以将图像保存在SQL Server上 Image 或MySQL as largeblob 。这段代码对我很有帮助。看看这个。

在这里保存图像

MemoryStream ms = new MemoryStream();
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, panel1.Bounds);
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // here you can change the Image format
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
ms.Close();

在这里你可以加载,但我使用了PictureBox控件。

MemoryStream ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
fotos.pictureBox1.Image = System.Drawing.Image.FromStream(ms);

希望有所帮助.

3
Leinad