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 2024-11-06 09:33  邢帅杰  阅读(17)  评论(0编辑  收藏  举报