最近兩天使用WebService開發訪問不同服務器把文件存放在同一個服務器上,文件傳輸上用到對象、文件和二進制Byte[]數組互相轉換,把代碼貼出來分享下。
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace WebDemo { public class Tools { /// <summary> /// 文件轉換為二進制Byte[]格式 /// </summary> /// <param name="filePath">文件路徑</param> /// <returns>二進制文件</returns> public static byte[] FileToByte(string filePath) { byte[] fileByte= File.ReadAllBytes(filePath); return fileByte; } /// <summary> /// 二進制Byte格式文件轉換為文件並保存在指定路徑 /// </summary> /// <param name="bytes">二進制文件</param> /// <param name="SavaPath">保存路徑</param> /// <returns>轉換結果</returns> public static bool ByteToFile(byte[] bytes,string SavaPath) { try { File.WriteAllBytes(SavaPath, fileByte); return true; } catch (Exception) { return false; } } /// <summary> /// 對象轉換為二進制Byte[]類型 /// </summary> /// <param name="obj">轉換的對象</param> /// <returns>二進制文件</returns> public static byte[] ObjectToByte(object obj) { MemoryStream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(memory, obj); byte[] bytes = stream.GetBuffer(); return bytes; } catch (Exception) { return new byte[0]; } finally { stream.Close(); } } /// <summary> /// 二進制Byte[]類型轉換為對象類型 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static object ByteToObject(byte[] bytes) { MemoryStream stream = new MemoryStream(bytes); IFormatter formatter = new BinaryFormatter(); try { object obj = formatter.Deserialize(stream); return obj; } catch (Exception) { } finally { stream.Close(); } } } }