您当前的位置:KKBlog > 学无止境 > ASP.NET

文件转换成base64 编码

        /// <summary>
        ///  文件转换成base64 编码
        /// </summary>
        private string file2Base64string(string str_file)
        {
            try
            {
                FileStream fstream = new FileStream(str_file, FileMode.Open);
                byte[] sourceBuffer = new byte[fstream.Length];
                fstream.Read(sourceBuffer, 0, sourceBuffer.Length);
                fstream.Close();
                fstream.Dispose();
                return Convert.ToBase64String(sourceBuffer);
            }
            catch
            {
                return "";
            }

        }
 
        /// <summary>
        ///  base64 编码字符串转换成文件
        /// </summary>
        private void Base64string2file(string str_base64, string str_file)
        {
            try
            {
                if (str_base64 != "")
                {
                    FileStream fstream = new FileStream(str_file, FileMode.Create);
                    MemoryStream stream = new MemoryStream(Convert.FromBase64String(str_base64));
                    byte[] sourceBuffer = new byte[stream.Length];
                    stream.Read(sourceBuffer, 0, sourceBuffer.Length);
                    fstream.Write(sourceBuffer, 0, sourceBuffer.Length);
                    fstream.Close();
                    stream.Close();
                    fstream.Dispose();
                    stream.Dispose();
                }
            }
            catch
            {
 
            }
            return;
        }
 
二维码
意见反馈 二维码