2017-07-29 27 views
0

我正在用C#编写一个HTML编辑器,其中包含FastColoredTextBox.dll组件。我有“另存为”选项的代码。但是当文件被保存时,我试着再次按下另存为选项,SaveFileDialog就会出现。我希望它保存到我们之前保存的文件中。这里是另存为代码:如何使用fastcoloredtextbox.dll组件保存HTML文件?

private void toolStripButton2_Click(object sender, EventArgs e) 
    { 
     SaveFileDialog sfd = default(SaveFileDialog); 
     if (FastColoredTextBox1.Text.Length > 0) 
     { 
      sfd = new SaveFileDialog(); 
      sfd.Filter = "HTML Files|.html|" + "All Files|*.*"; 

      sfd.DefaultExt = "html"; 

      sfd.ShowDialog(); 


      string location = null; 
      string sourcecode = FastColoredTextBox1.Text; 
      location = sfd.FileName; 
      if (!object.ReferenceEquals(sfd.FileName, "")) 
      { 
       using (System.IO.StreamWriter writer = new System.IO.StreamWriter(location, false)) 
       { 
        writer.Write(sourcecode); 
        writer.Dispose(); 
        this.Text = "Netplait 2.5.1 - " + System.IO.Path.GetFullPath(location); 
       } 
      } 
     } 
     if (Directory.Exists(sfd.FileName) == true) 
     { 
      string location = sfd.InitialDirectory; 
      File.WriteAllText(location, (FastColoredTextBox1.Text)); 
     } 
    } 

请帮忙。

+0

我不认为这有什么使用快速彩色文本框组件。您需要存储路径并不再次显示对话框。将路径存储在类变量中,并检查它是否在第一个if语句之前有值。如果确实如此,那么就保存到那条路上,否则就做你现在做的事。就目前而言,你没有逻辑来检查你是否曾经保存过一次。相反,你只是总是显示保存对话框。另外:不要使用ReferenceEquals检查字符串相等。使用string.Equals或==。由于它位于使用区块中,因此您无需在作家上调用Dispose。 – pinkfloydx33

回答

1

我必须说,这段代码对我来说似乎有点混乱。

为什么不直接创建对话框?

SaveFileDialog sfd = default(SaveFileDialog); 

而这一点,为什么不只是检查sfd.FileName != ""或更好!string.IsNullOrWhitespace(sfd.FileName)

if (!object.ReferenceEquals(sfd.FileName, "")) 

是我错了,那sfd.FileName应该返回一个文件名,而不是一个目录? 因为那么这个代码是没有意义的:

if (Directory.Exists(sfd.FileName) == true) 

无论如何,在打开对话框之前,你可以设置sfd.InitialDirectorysfd.FileName按文档

SaveFileDialog

+0

感谢您的建议,但这仍然不是我要找的。 – Roebebin

+0

我很抱歉,我不能有太大的帮助。我以为你想用以前的路径打开对话框,但我猜不是。 –

+0

没关系,我在那里得到了一点小费。 – Roebebin