【发布时间】:2013-04-04 00:15:23
【问题描述】:
我有以下代码:
打开文件代码
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html"; StreamReader sr = null;
if (ofd.ShowDialog() != DialogResult.Yes) return;
{
NewFile();
}
try
{
sr = new StreamReader(ofd.FileName);
this.Text = string.Format("{0} - Basic Word Processor", Path.GetFileName(ofd.FileName));
richTextBoxPrintCtrl1.Text = ofd.FileName;
richTextBoxPrintCtrl1.Text = sr.ReadToEnd();
filepath = ofd.FileName;
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch
{
}
finally
{
if (sr != null) sr.Close();
}
新文件代码
if (richTextBoxPrintCtrl1.Modified)
{
DialogResult r = MessageBox.Show(this, "Save Current Document?", "Save?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (r == DialogResult.Yes) SaveFile();
if (r == DialogResult.Cancel) return;
}
this.Text = string.Format("Untitled - Basic Word Processor");
richTextBoxPrintCtrl1.Text = "";
filepath = null;
}
}
将文件另存为代码
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
filepath = sfdSaveFile.FileName;
SaveFile();
this.Text = string.Format("{0} - Basic Word Processor", Path.GetFileName(sfdSaveFile.FileName));
}
catch (Exception exc)
{
}
保存文件代码
if (filepath == null)
{
SaveFileAs();
return;
}
StreamWriter sw = new StreamWriter(filepath);
//StreamWriter stwrite = null;
try
{
sw.WriteLine(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Modified = false;
sw.Close();
}
catch (Exception e)
{
MessageBox.Show("Failed to save file. \n" + e.Message);
}
finally
{
if (sw != null) sw.Close();
}
目前,程序会跳过 NewFile 事件(即使文本已被修改)。我怎样才能做到这一点,当我单击“打开”时,它会询问我是否要保存(如果文本被修改)。然后如果我点击取消,它会返回到表单?
对不起。我对编程真的很陌生,所以这都是一个学习曲线。
【问题讨论】:
-
要么你在不需要大括号的地方有大括号,要么你缺少很多代码。您是否使用调试器逐步完成了它? “程序跳过 NewFile 事件”是什么意思?事件是没有被调用还是它认为 .Modified 是假的?回到那些讨厌的大括号,它们根本不符合您的 if 语句。
-
我是新手。需要解释一下。对不起。
-
是的,很可能是这些大括号引起的,如果不是您关心的问题,那么可能是其他问题。
-
@Toby:编辑您的帖子并将整个 NewFile 事件,包括其中的方法声明。你现在拥有的东西没有意义。
-
朋友,我们都去过那里,只要继续练习,它就会比你想象的更快成为第二天性。但回到手头的问题......
标签: c# winforms visual-studio-2012 openfiledialog