Winform中如何排除保存文件对话框的文件路径?

How to exclude the path of the file of the SaveFileDialog box in Winform?

我正在使用 C# 在 Winform 中构建记事本演示应用程序。
当我单击“保存”或“另存为”按钮时,我想将表单的标题更改为不包括文件名路径的文件名。

(例如 "Demo.txt",但不是 "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;                             
    }

在上面的代码中,dlg.FileName returns文件名的完整路径。
在 OpenFileDialog 中,有 dlg.SafeFileName ,其中只有 returns 文件名。但是 SaveFileDialog 没有 属性.
如何在 SaveFileDialog 中只获取文件名?

使用 Path.GetFileName() 来自 System.IO 的方法:

Path.GetFileName(dlg.FileName);