从saveFileDialog获取没有文件名的路径?

时间:2012-10-06 14:31:08

标签: c# winforms

我尝试从SaveFileDialog获取我的路径而没有我的文件名,以便创建DirectoryInfo对象

private void btnBrowseCapture_Click(object sender, EventArgs e)
{
    SaveFileDialog saveFileDialogBrowse2 = new SaveFileDialog();
    saveFileDialogBrowse2.Filter = "Pcap file|*.pcap";
    saveFileDialogBrowse2.Title = "Save an pcap File";
    saveFileDialogBrowse2.ShowDialog();

    if (saveFileDialogBrowse2.FileName != "")
    {
        string str = saveFileDialogBrowse2.FileName;

    }
}

4 个答案:

答案 0 :(得分:8)

您也可以将System.IO.Path.GetDirectoryName用于此目的

System.IO.Path.GetDirectoryName(filePath)

答案 1 :(得分:2)

使用System.IO.FileInfo.DirectoryName属性获取文件目录的完整路径。


string fileName = @"C:\TMP\log.txt";
FileInfo fileInfo = new FileInfo(fileName);

Console.WriteLine(fileInfo.DirectoryName); // Output: "C:\TMP"

使用您的示例:

string str = saveFileDialogBrowse2.FileName;

FileInfo fileInfo = new FileInfo(str);
Console.WriteLine(fileInfo.DirectoryName);

答案 2 :(得分:2)

string fileName = @"C:\TMP\log.txt";
FileInfo fileInfo = new FileInfo(fileName);

Console.WriteLine(fileInfo.DirectoryName);

答案 3 :(得分:1)

您可以使用System.IO.Path.GetDirectoryName方法:

Console.WriteLine(System.IO.Path.GetDirectoryName(Filename));