private void MenuItemOpen_Click(object sender, EventArgs e)
{
if(needtosave==true)
{
DialogResult result=MessageBox.Show("文本内容已经改变,是否需要保存?","保存文件",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question);
if(result==DialogResult.Yes)
{
MenuItemSave_Click(sender,e);
needtosave=false;
richTextBoxText.Clear();
}
else if (result == DialogResult.Cancel)
{
return;
}
else
{
string file=GetOpenFile();
if(file==null)
{
return;
}
else
{
currenfilename=file;
OpenFile();
needtosave=false;
}
}
}
else
{
richTextBoxText.Clear();
string file = GetOpenFile();
if (file == null)
{
return;
}
else
{
currenfilename = file;
OpenFile();
needtosave = false;
}
}
}
private string GetOpenFile()
{
dlg = new OpenFileDialog();
dlg.Title = "打开文本文件";
dlg.ValidateNames = true;
dlg.CheckFileExists = true;
dlg.CheckPathExists = true;
dlg.ShowHelp = true;
dlg.Multiselect = true;
dlg.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
// string dir = Environment.GetFolderPath(Environment.SpecialFolder.Templates);
// dlg.InitialDirectory = dir;
if (dlg.ShowDialog() == DialogResult.OK)
{
return dlg.FileName;
}
else
{
return
null;
}
}
private void OpenFile()
{
try
{
FileStream fs = new FileStream(currenfilename, FileMode.Open, FileAccess.Read);
if (fs.CanRead)
{
FileInfo f = new FileInfo(currenfilename);
StreamReader sr = new StreamReader(fs, Encoding.Default);
string strline = sr.ReadLine();
if (strline != null)
{
//richTextBox1.Text += strline + "\n";
richTextBoxText.Text = strline + "\n";
strline = null;
}
sr.Close();
this.Text = f.Name;
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}