[英]Save and load MemoryStream to/from a file
我正在將一個結構序列化為MemoryStream
並且我想保存和加載序列化的結構。
那么,如何將MemoryStream
保存到文件中並從文件中加載回來?
您可以使用MemoryStream.WriteTo
或Stream.CopyTo
(框架版本Stream.CopyTo
支持)方法將內存流的內容寫入另一個流。
memoryStream.WriteTo(fileStream);
更新:
fileStream.CopyTo(memoryStream);
memoryStream.CopyTo(fileStream);
假設 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);
反過來(MemoryStream 到 FileStream):
using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write))
ms.CopyTo(file);
即使有異常(很可能在文件 I/O 上),流也應該真的被處理掉 - using 子句是我最喜歡的方法,所以為了編寫你的 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());
對於任何尋找簡短版本的人:
var memoryStream = new MemoryStream(File.ReadAllBytes("1.dat"));
File.WriteAllBytes("1.dat", memoryStream.ToArray());
寫入文件的組合答案可以是;
MemoryStream ms = new MemoryStream();
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
保存到文件中
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;
}
對於加載文件,我更喜歡這個
MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(file))
{
fs.CopyTo(ms);
}
我使用面板控件添加圖像甚至流視頻,但您可以將 SQL Server 上的圖像另存為Image或將 MySQL 保存為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();
在這里你可以加載,但我使用了一個圖片框控件。
MemoryStream ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
fotos.pictureBox1.Image = System.Drawing.Image.FromStream(ms);
希望有所幫助。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
namespace ImageWriterUtil
{
public class ImageWaterMarkBuilder
{
//private ImageWaterMarkBuilder()
//{
//}
Stream imageStream;
string watermarkText = "©8Bytes.Technology";
Font font = new System.Drawing.Font("Brush Script MT", 30, FontStyle.Bold, GraphicsUnit.Pixel);
Brush brush = new SolidBrush(Color.Black);
Point position;
public ImageWaterMarkBuilder AddStream(Stream imageStream)
{
this.imageStream = imageStream;
return this;
}
public ImageWaterMarkBuilder AddWaterMark(string watermarkText)
{
this.watermarkText = watermarkText;
return this;
}
public ImageWaterMarkBuilder AddFont(Font font)
{
this.font = font;
return this;
}
public ImageWaterMarkBuilder AddFontColour(Color color)
{
this.brush = new SolidBrush(color);
return this;
}
public ImageWaterMarkBuilder AddPosition(Point position)
{
this.position = position;
return this;
}
public void CompileAndSave(string filePath)
{
//Read the File into a Bitmap.
using (Bitmap bmp = new Bitmap(this.imageStream, false))
{
using (Graphics grp = Graphics.FromImage(bmp))
{
//Determine the size of the Watermark text.
SizeF textSize = new SizeF();
textSize = grp.MeasureString(watermarkText, font);
//Position the text and draw it on the image.
if (position == null)
position = new Point((bmp.Width - ((int)textSize.Width + 10)), (bmp.Height - ((int)textSize.Height + 10)));
grp.DrawString(watermarkText, font, brush, position);
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Watermarked image to the MemoryStream.
bmp.Save(memoryStream, ImageFormat.Png);
memoryStream.Position = 0;
// string fileName = Path.GetFileNameWithoutExtension(filePath);
// outPuthFilePath = Path.Combine(Path.GetDirectoryName(filePath), fileName + "_outputh.png");
using (FileStream file = new FileStream(filePath, FileMode.Create, System.IO.FileAccess.Write))
{
byte[] bytes = new byte[memoryStream.Length];
memoryStream.Read(bytes, 0, (int)memoryStream.Length);
file.Write(bytes, 0, bytes.Length);
memoryStream.Close();
}
}
}
}
}
}
}
用法 :-
ImageWaterMarkBuilder.AddStream(stream).AddWaterMark("").CompileAndSave(filePath);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.