简体   繁体   English

从包含文件名的路径中获取没有文件名的完整路径

[英]Get full path without filename from path that includes filename

Is there anything built into System.IO.Path that gives me just the filepath? System.IO.Path中是否有任何内容仅提供文件路径?

For example, if I have a string例如,如果我有一个string

@"c:\\webserver\\public\\myCompany\\configs\\promo.xml", @"c:\\webserver\\public\\myCompany\\configs\\promo.xml",

is there any BCL method that will give me是否有任何 BCL 方法可以给我

"c:\\webserver\\public\\myCompany\\configs\\"? “c:\\webserver\\public\\myCompany\\configs\\”?

Path.GetDirectoryName() ... but you need to know that the path you are passing to it does contain a file name; Path.GetDirectoryName() ... 但你需要知道你传递给它的路径确实包含一个文件名; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).它只是从路径中删除最后一位,无论是文件名还是目录名(它实际上不知道是哪个)。

You could validate first by testing File.Exists() and/or Directory.Exists() on your path first to see if you need to call Path.GetDirectoryName您可以首先通过在您的路径上测试File.Exists()和/或Directory.Exists()来验证是否需要调用Path.GetDirectoryName

Console.WriteLine(Path.GetDirectoryName(@"C:\hello\my\dear\world.hm")); 

Path.GetDirectoryName()返回目录名称,因此对于您想要的(带有尾随反实线字符),您可以调用Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar

    string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml";

    string currentDirectory = Path.GetDirectoryName(fileAndPath);

    string fullPathOnly = Path.GetFullPath(currentDirectory);

currentDirectory: c:\\webserver\\public\\myCompany\\configs当前目录:c:\\webserver\\public\\myCompany\\configs

fullPathOnly: c:\\webserver\\public\\myCompany\\configs fullPathOnly: c:\\webserver\\public\\myCompany\\configs

Use GetParent() as shown, works nicely.如图所示使用GetParent() ,效果很好。 Add error checking as you need.根据需要添加错误检查。

var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;

I used this and it works well:我用过这个,效果很好:

string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));

foreach (string file in filePaths)
{   
    if (comboBox1.SelectedItem.ToString() == "")
    {
        if (file.Contains("c"))
        {
            comboBox2.Items.Add(Path.GetFileName(file));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM