廢話不多說,直接看代碼!!!
#region 二進制數據轉換爲附件
/// <summary>
/// 二進制數據轉換爲附件
/// </summary>
/// <param name="data">二進制數據</param>
/// <param name="fileName">附件.後綴</param>
/// <param name="savePath">保存路徑</param>
/// <returns>保存的相對路徑</returns>
public string ByteConvertFile(byte[] data, string fileName, string savePath)
{
if (!System.IO.Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
savePath += fileName;
FileStream fs;
if (System.IO.File.Exists(savePath))
{
fs = new FileStream(savePath, FileMode.Truncate);
}
else
{
fs = new FileStream(savePath, FileMode.CreateNew);
}
BinaryWriter br = new BinaryWriter(fs);
br.Write(data, 0, data.Length);
br.Close();
fs.Close();
return savePath;
}
#endregion
#region 附件轉換二進制數據(用於保存數據庫)
/// <summary>
/// 附件轉換二進制數據(用於保存數據庫)
/// </summary>
/// <param name="filePath">附件路徑</param>
/// <returns>二進制</returns>
private byte[] fileConvertByte(string filePath)
{
byte[] bytContent = null;
System.IO.FileStream fs = null;
System.IO.BinaryReader br = null;
try
{
fs = new FileStream(filePath, System.IO.FileMode.Open);
}
catch
{
}
br = new BinaryReader((Stream)fs);
bytContent = br.ReadBytes((Int32)fs.Length);
return bytContent;
}
#endregion
//測試方法
protected void Button1_Click1(object sender, EventArgs e)
{
string newWord = ByteConvertFile(fileConvertByte(@"D:\Portal\UpLoadFiles\sP2_20110925210928.jpg"), "測試成功.jpg", @"F:\abc\");
Label1.Text = newWord;
}