C#文件操作–读写文本文件,保存后打开是乱码
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();
}
private void label2_Click(object sender, EventArgs e)
{
}
string path = @"G:\SoftwareLearning\C#resource\chapter01\WindowsFormsApp1\22.txt";
private void button1_Click(object sender, EventArgs e)
{
string idMessage = textBox1.Text; //获得文本框中信息 UTF8
FileStream fsw = new FileStream(path, FileMode.OpenOrCreate);
byte[] writeBytes = Encoding.UTF8.GetBytes(idMessage);
for (int i = 0; i < writeBytes.Length; i++)
{
writeBytes[i] += 50;
}
fsw.Write(writeBytes, 0, writeBytes.Length);
fsw.Close();
}
private void button2_Click(object sender, EventArgs e)
{
FileStream fsr = new FileStream(path, FileMode.Open);
byte[] readBytes = new byte[1024 * 1024];
int count = fsr.Read(readBytes, 0, readBytes.Length);
for (int i = 0; i < readBytes.Length; i++)
{
readBytes[i] -= 50;
}
string readStr = Encoding.UTF8.GetString(readBytes, 0, count);
fsr.Close();
textBox2.Text = readStr;
}
}
}
运行结果如下: