距離上一次寫博客已經是long long ago 的事情了。。。。
最近項目告一段落,開始整理之前做過的東西。
廢話不多說,直接貼代碼
1 public class FileBinaryConvertHelper 2 { 3 /// <summary> 4 /// 將文件轉化位byte數組 5 /// </summary> 6 /// <param name="Path">文件地址</param> 7 /// <returns>轉換為的byte數組</returns> 8 public static byte[] FileBytes(string Path) 9 { 10 if(!System.IO.File.Exists(Path)) 11 { 12 return new byte[0]; 13 } 14 FileInfo fi = new FileInfo(Path); 15 byte[] buff=new byte[fi.Length]; 16 FileStream fs = fi.OpenRead(); 17 fs.Read(buff,0,Convert.ToInt32(fs.Length)); 18 fs.Close(); 19 return buff; 20 } 21 /// <summary> 22 /// 將byte數組轉換為文件並保存到指定地址 23 /// </summary> 24 /// <param name="buff">byte數組</param> 25 /// <param name="savepath">保存地址</param> 26 public static void BytesFile(byte[] buff,string savepath) 27 { 28 if(System.IO.File.Exists(savepath)) 29 { 30 System.IO.File.Delete(savepath); 31 } 32 FileStream fs = new FileStream(savepath,FileMode.CreateNew); 33 BinaryWriter bw = new BinaryWriter(fs); 34 bw.Write(buff,0,buff.Length); 35 fs.Close(); 36 } 37 }
1 private static void UploadFile() 2 { 3 OpenFileDialog dialog = new OpenFileDialog(); 4 dialog.Filter = "壓縮文件|*.zip"; 5 dialog.CheckFileExists = true; 6 dialog.ShowDialog(); 7 if(!string.IsNullOrWhiteSpace(dialog.FileName)) 8 { 9 try 10 { 11 byte[] byteArray = FileBinaryConvertHelper.FileBytes(dialog.FileName);//文件轉換成byte二進制數組 12 FileBinaryConvertHelper.BytesFile(byteArray,@"D:\test2\\新建文件夾\\ddd.zip");//二進制數組轉換為zip文件 13 14 } 15 catch(Exception ex) 16 { 17 } 18 } 19 }
如有不當之處,請多多指教!
蟹蟹!
