各位,我在用C#写记事本的时候出现了个问题,求教各位,万分感激!
各位,我在看视频教程学开发记事本程序的时候发现一个问题,目前简单的实现了“新建”、“打开”、“保存”、“另存为”功能,但发现有个乱码问题,就是在运行程序后编辑了一段文本后另存为保存在一个地址中,在用程序打开刚才的那保存的TXT文件就全都是乱码,打开不是用程序另存为的TXT文件就不会出现这种情况,还请各位赐教。下面附上源码:using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using
namespace Notepad
{
public partial class FormMain : Form
{
string currentFileName = "新建文本文档.txt";
public FormMain()
{
InitializeComponent();
}
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
//MessageBox.Show("test123");
this.richTextBox1.Text = "";
using (StreamWriter sw = new StreamWriter(currentFileName))
{
}
}
/// <summary>
/// read file
/// </summary>
/// <param name="file">file name</param>
void openFile(string file)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(file, Encoding.GetEncoding(0)))
{
string text = "";
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
text += line + "\n";
}
this.richTextBox1.Text = text;
}
}
catch (Exception ex)
{
// Let the user know what went wrong.
//Console.WriteLine("The file could not be read:");
//Console.WriteLine(e.Message);
MessageBox.Show(ex.Message);
}
}
void writeFile(string file)
{
using (StreamWriter sw = new StreamWriter(file))
{
foreach (string s in this.richTextBox1.Lines)
{
sw.WriteLine(s);
}
}
}
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
this.currentFileName = this.openFileDialog1.FileName;
openFile(this.openFileDialog1.FileName);
}
}
private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult dr = this.saveFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
this.currentFileName = this.openFileDialog1.FileName;
writeFile(this.saveFileDialog1.FileName);
}
}
private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
{
writeFile(this.currentFileName);
}
}
}