C# Base64 Encoding and Decoding
It make a record .
using dotNet Framwork 4.5
using dotNet Framwork 4.5
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace base64dne
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
cbEncoding.Sorted = true;
}
private void Form1_Load(object sender, EventArgs e)
{
//comboBox initial (Get Encoding list)
foreach (EncodingInfo ei in Encoding.GetEncodings())
{
cbEncoding.Items.Add(ei.Name);
}
cbEncoding.Text = Encoding.Default.BodyName;
}
/// <summary>
/// Base64 Decoding
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDEC_Click(object sender, EventArgs e)
{
if (cbEncoding.Text == "")
{
return;
}
string source = tbSource.Text;
var data = Convert.FromBase64String(source);
string result = Encoding.GetEncoding(cbEncoding.Text).GetString(data);
tbOut.Text = result;
}
/// <summary>
/// Base64 Encoding
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnENC_Click(object sender, EventArgs e)
{
if (cbEncoding.Text == "")
{
return;
}
string source = tbSource.Text;
byte[] bytes = Encoding.GetEncoding(cbEncoding.Text).GetBytes(source);
string data = Convert.ToBase64String(bytes);
tbOut.Text = data;
}
/// <summary>
/// Get source data from text file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Choose Source text file";
ofd.InitialDirectory = "C:\\";
ofd.Filter = "Text File(*.txt)|*.txt|All files(*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
using(StreamReader sr = new StreamReader(ofd.FileName))
{
string data = sr.ReadToEnd();
tbSource.Text = data;
}
}
}
/// <summary>
/// save result data to text file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Choose File to save result";
sfd.InitialDirectory = "C:\\";
sfd.Filter = "Text File(*.txt)|*.txt|Xml file(*.xml)|*.xml|Common File(*.csv)|*.csv|Other files(*.*)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
if (sfd.FileName != "")
{
string ext = Path.GetExtension(sfd.FileName);
if (ext != "txt" && ext != "xml" && ext != "csv")
{
MessageBox.Show("Attention ! your file extension may not supported or not be right encoding !");
}
//that file will be overwrite if file exists
using(StreamWriter sw = new StreamWriter(sfd.FileName))
{
sw.Write(tbOut.Text);
}
}
else
{
MessageBox.Show("not specifity file name !");
}
}
}
}
}
留言