用C# Winform写了一个可以打开任何文件的转换程序,作用很简单:就是把被打开文件作为二进制文件读入,然后将二进制转为对应的16进制数据,并将此数据以明码(ASCII码)的形式存入指定的txt文件,16个字节一行。
代码是在VS2017下,用C# winform做的,只在Form1 添加了两个按钮:button1与 button2,分别将Form1的button1_Click和button2_Click添加到设计器里的对应按钮的click事件里即可。
直接上源码了:
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool flag=false; //指示输入文件是否选好
string file_in;
string fold;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = System.Environment.CurrentDirectory;//获取当前目录
ofd.Filter = "exe文件(*.exe;)|(*.exe;*.exe;)|所有文件|*.*";
ofd.ValidateNames = true;
ofd.CheckPathExists = true;
ofd.CheckFileExists = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
file_in= ofd.FileName;
flag = true; //文件已选好,将标记符置为真
fold = System.IO.Path.GetFullPath(ofd.FileName);//获取选好文件的所在目录
MessageBox.Show("已载入文件:" + file_in);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (flag) //check whether there is inputfile already
{
string f = file_in.Substring(file_in.LastIndexOf("\\") + 1, (file_in.LastIndexOf(".") - file_in.LastIndexOf("\\") - 1)); //去除扩展名之后的文件名
string txtfilename;
txtfilename = f + ".txt";
BinaryReader br;
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.RestoreDirectory = false; //若为false,则打开对话框后为上次的目录。若为true,则为初始目录
fileDialog.Title = "请选择文件";
fileDialog.Filter = "txt文件(*.txt;)|(*.txt;*.TXT;)|所有文件(*.*)|*.*";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
try
{
br = new BinaryReader(new FileStream(file_in, FileMode.Open));
}
catch (IOException)
{
Console.WriteLine("无法打开文件" + file_in);
return;
}
string name = fileDialog.FileName; //保存文件的名字
FileInfo myFile = new FileInfo(name);
StreamWriter sw = myFile.CreateText();
//begin to output data to txt
byte bb;
int i = 0;
while (br.BaseStream.Position < br.BaseStream.Length)
{
bb = br.ReadByte();
int ii = bb;
sw.Write("{0:X} ", ii.ToString("X2").PadLeft(2, '0'));
i++;
if (i % 16 == 0) { sw.WriteLine(); }
}
br.Close();
sw.Close();
MessageBox.Show("文件"+name+"已保存");
}
}
else MessageBox.Show("尚未导入要转换的文件!请先点文件导入");
}
}
}
以下是调试成功的画面:
希望可以帮到大家,谢谢!!!