二進制數據和文件之間相互轉換的方法

在網上尋找的方法,能夠實現把數據庫中的二進制數據轉換成文件,也能夠把本地的文件轉成二進制的數據。二進制的圖片數據能夠用response對象直接輸出給瀏覽器,比較方便~ 話很少說,代碼送上!數據庫

 

 

/// 
/// 文件轉爲 二進制
/// 
/// 文件路徑
/// 
public static byte[] File2Bytes(string path)
{
if (!System.IO.File.Exists(path))
{
return new byte[0];
}
FileInfo fi = new FileInfo(path);
byte[] buff = new byte[fi.Length];
FileStream fs = fi.OpenRead();
fs.Read(buff, 0, Convert.ToInt32(fs.Length));
fs.Close();
return buff;
}
/// 
/// 將byte數組轉換爲文件並保存到指定地址
/// 
/// byte數組
/// 保存地址
public static void Bytes2File(byte[] buff, string savepath)
{
if (System.IO.File.Exists(savepath))
{
System.IO.File.Delete(savepath);
}
FileStream fs = new FileStream(savepath, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, 0, buff.Length);
bw.Close();
fs.Close();
}
數組

相關文章
相關標籤/搜索