1、BIN文件
(1) 创建布局文件并添加openFileDialog和saveFileDialog
(2)打开按钮事件
FileStream Myfile;
BinaryReader binreader;
BinaryWriter binwriter;
int file_len;//bin文件长度
int count = 1;
byte[] binchar = new byte[] { };//文件数据存储
private void button1_Click(object sender, EventArgs e)//打开文件按钮
{
openFileDialog1.Filter = "*.bin|*.BIN";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName.Text = openFileDialog1.FileName;
StringBuilder str = new StringBuilder();
Myfile = new FileStream(openFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
binreader = new BinaryReader(Myfile);
binwriter = new BinaryWriter(Myfile);
file_len = (int)Myfile.Length;//获取bin文件长度
binchar = binreader.ReadBytes(file_len);
foreach (byte j in binchar)
{
str.Append(j.ToString("X2") + " ");
if (count >= 8)
{
count = 0;
str.Append("\r\n");
}
count++;
}
text2.Text = str.ToString();
MessageBox.Show("查询成功!");
}
}
(3)写入按钮事件
private Byte[] AsciiCharToByte8(string Str)
{
Byte[] tByte = Encoding.ASCII.GetBytes(Str);
return tByte;
}
private void button2_Click(object sender, EventArgs e)//写入文件按钮
{
byte[] insert_data = AsciiCharToByte8("hello");//在打开的文件前加入hello
byte[] binchar0 = new byte[file_len + 5];
for (int i = 0; (i < insert_data.Length); i++)
{
binchar0[i] = insert_data[i];
}
for(int i=0;i<file_len;i++)
{
binchar0[i + 5] = binchar[i];
}
Myfile.Seek(0, SeekOrigin.Begin);
binwriter.Write(binchar0);
binreader.Close();
binwriter.Close();
Myfile.Close();
}
2、TXT文件
(1)创建布局界面
(2)打开按钮事件
private void button_open_txt_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "(*.txt)|*.txt";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName_txt.Text = openFileDialog1.FileName;
textBox_display_txt.Clear();
StreamReader sr = new StreamReader(openFileDialog1.FileName, System.Text.Encoding.Default);
string line;
while ((line = sr.ReadLine()) != null)
{
textBox_display_txt.Text += line;
}
sr.Close();
}
}
(3)写入按钮事件
private void button_write_txt_Click(object sender, EventArgs e)
{
bool flag = true;
StreamWriter sw = null;
try
{
sw = new StreamWriter(openFileDialog1.FileName);//创建StreamWriter对象
sw.WriteLine(textBox_display_txt.Text);
}
catch (Exception ex)
{
Console.WriteLine("写入流异常:" + ex.ToString());
flag = false;
}
finally
{
sw.Close();//确保最后总会关闭流
Console.WriteLine("写入流关闭");
}
if (flag)
{
MessageBox.Show("文件已保存!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}