posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

复制代码
public class FileUtil
{
    /// <summary>
    /// 文件转换成Base64字符串
    /// </summary>
    /// <param name="fileName">文件绝对路径</param>
    /// <returns></returns>
    public static String FileToBase64(string fileName)
    {
        string strRet = string.Empty;
        try
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, bt.Length);
                strRet = Convert.ToBase64String(bt);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return strRet;
    }

    /// <summary>
    /// 文件转Base64
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="base64Str"></param>
    public static string FileToBase64(Stream stream)
    {
        using (BinaryReader binReader = new BinaryReader(stream))
        {
            byte[] bytes = binReader.ReadBytes(Convert.ToInt32(stream.Length));
            string base64Str = Convert.ToBase64String(bytes);
            return base64Str;
        }
    }

    /// <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);
            using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
            {
                fs.Write(buffer, 0, buffer.Length);
                bTrue = true;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return bTrue;
    }
}
复制代码

 

posted on   邢帅杰  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示