How do i save a file in fastcoloredtextbox?

617 Views Asked by At

I'm developing a syntax editor in C# where you can write code in the FastColoredTextBox component, then saving it as a .html file. However, I have the code for the Save As option. The only problem I have is when the user saves the .html file, the same Save As dialog pops up. But we have already saved it before. I want to just press Ctrl+Son the keyboard and it will automatically save the file changes after saving as a .html file of course.

Here's the code I have for the Save As option.

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();
            }
        }
    }
    if (Directory.Exists(sfd.FileName) == true)
    {
        string location = sfd.InitialDirectory;
        File.WriteAllText(location, (FastColoredTextBox1.Text));
    }
}

Can anyone help me to achieve this? Please help.

1

There are 1 best solutions below

0
On BEST ANSWER

You should do what the others suggested about saving it as a text file with a .html as extension as well, but I'm here to answer your ctrl + s question. This is assuming you're on a winform (because you haven't specified yet):

yourForm.KeyPreview = true;
yourForm.KeyDown += new KeyEventHandler(Form_KeyDown);

and your handler should look something like this:

    void Form_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.KeyCode == Keys.S)
        {
            string sourceCode = FastColoredTextBox1.Text;
            // not sure what's going on for you "location" but you need to do that logic here too
            File.WriteAllText(location, sourceCode);
            e.SuppressKeyPress = true;
        }
    }

Hope that helps bud