C# 将指定文件转换成Base64字符串
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>
/// 将指定文件转换成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];
// 调用read读取方法
fileStream.Read(bt, 0, bt.Length);
base64Str = Convert.ToBase64String(bt);
}
return base64Str;
}
}
}