牛骨文教育服务平台(让学习变的简单)
博文笔记

C#将文件进行Base64转码解码

创建时间:2017-01-07 投稿人: 浏览次数:7777

是用C#将文件进行Base64转码解码,支持TXT、DOC、XLS等文件。

先上图:

第一个文本框是源文件地址,第二个文本框是存放Base64码的一个文本文件,第三个文本框是解码后的文件路径。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Base64Demo
{
    public partial class Form1 : Form
    {
        private string base64Str;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //

            string path = textBox1.Text;  //界面上第一个文件路径
            string tempPath = textBox3.Text; //界面上第二个文件路径
            FileStream filestream = new FileStream(path, FileMode.Open);

            byte[] bt = new byte[filestream.Length];

            //调用read读取方法
            filestream.Read(bt, 0, bt.Length);
            this.base64Str = Convert.ToBase64String(bt);
            filestream.Close();

            //将Base64串写入临时文本文件
            if (File.Exists(tempPath))
            {
                File.Delete(tempPath);
            }
            FileStream fs = new FileStream(tempPath, FileMode.Create);
            byte[] data = System.Text.Encoding.Default.GetBytes(this.base64Str);
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string outPath = textBox2.Text;  //界面上第三个文件路径
            var contents = Convert.FromBase64String(this.base64Str);
            using (var fs = new FileStream(outPath, FileMode.Create, FileAccess.Write))
            {
                fs.Write(contents, 0, contents.Length);
                fs.Flush();
            }
        }
    }
}


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。