c#中文件与二进制流文件的转换

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

     /// <summary>
    /// 将文件转换成二进制
    /// </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;
    }

 

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

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

posted @ 2013-07-12 11:47  丶神經病  阅读(642)  评论(0编辑  收藏  举报