發(fā)布時間:2020-08-06 15:30 作者:獨孤劍 閱讀:4445
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ConsoleApp18 { class Program { static void Main(string[] args) { string base64Str = FileToBase64Str("D:\\001.txt"); Console.WriteLine(); } /// <summary> /// 將指定文件轉(zhuǎn)換成Base64字符串 /// </summary> /// <param name="path">文件路徑</param> /// <returns>返回Base64字符串</returns> public static string FileToBase64Str(string path) { // 空路徑名是不合法的 if (string.IsNullOrEmpty(path)) { throw new ArgumentException("Empty path name is not legal.", "path"); } // 判斷路徑是否存在 if (!File.Exists(path)) { throw new FileNotFoundException("Could not find file '" + path + "'.", path); } string base64Str; using (System.IO.FileStream fileStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { byte[] bt = new byte[fileStream.Length]; // 調(diào)用read讀取方法 fileStream.Read(bt, 0, bt.Length); base64Str = Convert.ToBase64String(bt); } return base64Str; } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞