日期:2014-05-18 浏览次数:21042 次
openFile.ShowDialog();
strFileName = openFile.FileName;
if (strFileName == "") return;
//读取txt文件
StreamReader sr = new StreamReader(strFileName,System.Text.Encoding.Default);
string strText = sr.ReadToEnd();
sr.Close();
sr.Dispose();
textBox1=strText ;
------解决方案--------------------
public class TextForm : Form
{
TextBox _edit;
string _filename;
bool _dirty;
public TextForm()
{
_edit = new TextBox();
_edit.Dock = DockStyle.Fill;
_edit.TextChanged = (sender, e) => { _dirty = true; };
this.Controls.Add(_edit);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "文本文件|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
{
_filename = dlg.FileName;
_edit.Text = System.IO.File.ReadAllText(_filename);
_dirty = false;
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (!e.Cancel && _dirty)
{
DialogResult dr = MessageBox.Show("文件已更改,是否保存?", "确认",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
if (_filename == null)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "文本文件|*.txt";
if (dlg.ShowDialog() == DialogResult.OK)
_filename = dlg.FileName;
}
if (_filename != null)
{
System.IO.File.WriteAllText(_filename, _edit.Text);
}
}
else if (dr == DialogResult.Cancel)
e.Cancel = true;
}
}
}