0

I am building a Notepad demo application in Winform using C#.
When I click the Save or SaveAs button, I want to change the Title of the Form to the File Name excluding the path of the file name.

(e.g "Demo.txt", but not "D:\Demo.txt")

private string fileName;
private void mnuSaveAs_Click(object sender, EventArgs e)
    {
        SaveFileDialog dlg = new SaveFileDialog();
        dlg.Filter = "Text Documents(*.txt)|*.txt|All Files(*.*)|*.*";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            fileName = dlg.FileName;
            StreamWriter sw = new StreamWriter(fileName);
            sw.Write(txtMain.Text);
            sw.Close();
        }

        this.Text = dlg.FileName;                             
    }

In the above code, dlg.FileName returns the full path of the file name.
In the OpenFileDialog, there is dlg.SafeFileName which only returns the file name. But SaveFileDialog does not have that property.
How can I get only the file name in SaveFileDialog?

1 Answers1

0

Use Path.GetFileName() Method from System.IO:

Path.GetFileName(dlg.FileName);
user9923760
  • 546
  • 1
  • 8
  • 16