C# 文件、byte相互转换

文件转byte数组:

 1         /// <summary>
 2         /// 将文件转换为byte数组
 3         /// </summary>
 4         /// <param name="path">文件地址</param>
 5         /// <returns>转换后的byte数组</returns>
 6         public static byte[] File2Bytes(string path)
 7         {
 8             if (!System.IO.File.Exists(path))
 9             {
10                 return new byte[0];
11             }
12 
13             FileInfo fi = new FileInfo(path);
14             byte[] buff = new byte[fi.Length];
15 
16             FileStream fs = fi.OpenRead();
17             fs.Read(buff, 0, Convert.ToInt32(fs.Length));
18             fs.Close();
19 
20             return buff;
21         }

base64转文件:

 1         /// <summary>
 2         /// base64转文件
 3         /// </summary>
 4         /// <param name="base64Stream"></param>
 5         /// <returns></returns>
 6         public static string SaveLicensePhoto(string base64Stream, string savepath)
 7         {
 8             //string filepath = string.Empty;
 9             byte[] bytes = Convert.FromBase64String(base64Stream);
10             MemoryStream ms = new MemoryStream();
11             ms.Write(bytes, 0, bytes.Length);
12             Bitmap bmp = new Bitmap(ms);
13 
14             string path = CommonHelper.MapPath(savepath);
15             if (!Directory.Exists(path))
16             {
17                 Directory.CreateDirectory(path);
18             }
19             string filename = Guid.NewGuid().ToString() + ".jpg";
20             bmp.Save(path + filename);
21             return savepath + filename;
22         }

猜你喜欢

转载自www.cnblogs.com/qinaqina/p/11876429.html