using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace ToBase64
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
byte[] binaryData;
byte[] frombaseData;
string base64String,frombase64;
private void button1_Click(object sender, EventArgs e)
{
try //读取当前目录下的base.txt文件
{
FileStream inFile = new System.IO.FileStream("base.txt",FileMode.Open,FileAccess.Read);
binaryData=new Byte[inFile.Length];
inFile.Read(binaryData, 0,(int)inFile.Length);
inFile.Close();
}
catch (Exception err)
{
label1.Text = err.Message.ToString();
}
try//转换
{
base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);
}
catch(Exception err)
{
label1.Text=err.Message.ToString();
}
try//将转换后的数据写入到当前目录result.txt中
{
StreamWriter sw = new StreamWriter("result.txt", false, System.Text.Encoding.ASCII);
sw.WriteLine(base64String);
sw.Close();
}
catch (Exception err)
{
label1.Text = err.Message.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{//读取上次转换后的文件
char[] base64CharArray;
StreamReader inFile = new StreamReader("result.txt", System.Text.Encoding.ASCII);
base64CharArray = new char[inFile.BaseStream.Length];
inFile.Read(base64CharArray, 0, (int)inFile.BaseStream.Length);
frombase64 = new string(base64CharArray);
}
catch(Exception err)
{
label1.Text = err.Message.ToString();
}
try
{//转换
frombaseData = System.Convert.FromBase64String(frombase64);
}
catch(Exception err)
{
label1.Text = err.Message.ToString();
}
try
{//写入新的文本文件,和原来的内容相符
FileStream fs = new FileStream("frombase64.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write);
fs.Write(frombaseData, 0, binaryData.Length);
fs.Close();
}
catch (Exception err)
{
label1.Text = err.Message.ToString();
}
}
}
}