C#二进制格式与文件相互转换

将文件转换成二进制方法:

     ///


    /// 将文件转换成二进制
    ///

    /// 文件路径
    ///
    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;
    }

 

将二进制转换成文件方法:

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);   //二进制转换成文件
}
catch(Exception ex)
{
     //抛出异常信息
}
 finally
{
     fstream.Close();    

 

 

附加:二进制与图片互转

    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); //将图像序列化成二进制流
                        
            stream.Position
= 0;
            Image bb
= (Image)formatter.Deserialize(stream);  //将二进制流序列成Image
            
  

你可能感兴趣的:(C#二进制格式与文件相互转换)