您的位置:首页 > 其它

编码文件为Base64编码形式和解码Base64编码文件

2007-11-13 17:09 295 查看


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();

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: