C#二进制格式与文件相互转换
將文件轉(zhuǎn)換成二進(jìn)制方法:
???? /// <summary>
??? /// 將文件轉(zhuǎn)換成二進(jìn)制
??? /// </summary>
??? /// <param name="Path">文件路徑</param>
??? /// <returns></returns>
??? public static byte[] ConvertToBinary(string Path)
??? {
??????? FileStream stream = new FileInfo(Path).OpenRead();
??????? byte[] buffer = new byte[stream.Length];
??????? stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
??????? return buffer;
??? }
?
將二進(jìn)制轉(zhuǎn)換成文件方法:
using System.IO;
?
string filePath = "D:\\a.jpg";?? //文件路徑
byte[] br = ConvertToBinary(filePath);
FileStream fstream = File.Create(filePath, br.Length);
try
{??
?????fstream.Write(br, 0, br.Length);?? //二進(jìn)制轉(zhuǎn)換成文件
}
catch(Exception ex)
{
?????//拋出異常信息
}
?finally
{
?????fstream.Close();????
}?
?
?
附加:二進(jìn)制與圖片互轉(zhuǎn)
??? Image aa = new Bitmap(@"E:\photo\tm.jpg");
????System.IO.MemoryStream stream = new System.IO.MemoryStream();
?????System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter?
???? = new?? System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, aa); //將圖像序列化成二進(jìn)制流
????????????????????????
??????????? stream.Position = 0;
??????????? Image bb = (Image)formatter.Deserialize(stream);? //將二進(jìn)制流序列成Image
??????????????
轉(zhuǎn)載于:https://www.cnblogs.com/lmjob/archive/2008/10/07/1305638.html
總結(jié)
以上是生活随笔為你收集整理的C#二进制格式与文件相互转换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RouterOs建立PPPoE虚拟拨号服
- 下一篇: Linq to sql和lambda