.NET base64與檔案互轉方法、 byte[]與檔案互轉方法
阿新 • • 發佈:2019-02-13
base64與檔案互轉
/// <summary> /// 檔案轉換成Base64字串 /// </summary> /// <param name="fileName">檔案絕對路徑</param> /// <returns></returns> public static String FileToBase64(string fileName) { string strRet =""; try { FileStream fs = new FileStream(fileName, FileMode.Open); byte[] bt = new byte[fs.Length]; fs.Read(bt, 0, bt.Length); strRet = Convert.ToBase64String(bt); fs.Close(); } catch (Exception ex) { strRet = null; } return strRet; } /// <summary> /// Base64字串轉換成檔案 /// </summary> /// <param name="strInput">base64字串</param> /// <param name="fileName">儲存檔案的絕對路徑</param> /// <returns></returns> public static bool Base64ToFileAndSave(string strInput, string fileName) { bool bTrue = false; try { byte[] buffer = Convert.FromBase64String(strInput); FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate); fs.Write(buffer, 0, buffer.Length); fs.Close(); bTrue = true; } catch (Exception ex) { } return bTrue; }
byte[]與檔案互轉
/// <summary> /// 建立檔案路徑 /// </summary> /// <param name="filepath"></param> /// <returns></returns> public static void CreatePath(string filepath) { if (!Directory.Exists(filepath)) { var securityRules = new DirectorySecurity(); securityRules.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow)); securityRules.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow)); securityRules.AddAccessRule(new FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow)); Directory.CreateDirectory(filepath, securityRules); } } /// <summary> /// 檔案轉byte[] /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static byte[] ReadFileToByte(string fileName) { FileStream pFileStream = null; byte[] pReadByte = new byte[0]; try { pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(pFileStream); r.BaseStream.Seek(0, SeekOrigin.Begin); //將檔案指標設定到檔案開 pReadByte = r.ReadBytes((int)r.BaseStream.Length); return pReadByte; } catch { return pReadByte; } finally { if (pFileStream != null) { pFileStream.Close(); } } } /// <summary> /// 儲存檔案 /// </summary> /// <param name="file"></param> /// <param name="fileName"></param> /// <returns></returns> public static bool SaveFile(byte[] file,string fileName) { bool isSave = false; try { using (var ms = new MemoryStream()) { MemoryStream m = new MemoryStream(file); FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate); m.WriteTo(fs); m.Close(); fs.Close(); } isSave = true; } catch(Exception ex) { } return isSave; }