简体   繁体   中英

How to get parent directory in a path c#?

这是我的路径示例E:\\test\\img\\sig.jpg我想让E:\\test\\img创建目录,我尝试拆分,但它是img,所以我尝试使用Directory.CreateDirectory函数,路径为E:\\test\\img\\sig.jpg\\说个主意?

The recommended way is to use Path.GetDirectoryName() :

string file = @"E:\test\img\sig.jpg";
string path = Path.GetDirectoryName(file); // results in @"E:\test\img"

使用Path.GetDirectoryName返回指定路径字符串的目录信息。

string directoryName = Path.GetDirectoryName(filePath);

The Path class contains a lot of useful methods for path handling, which are more reliable than manual string manipulation:

var directoryComponent = Path.GetDirectoryName(@"E:\test\img\sig.jpg");
// yields `E:\test\img`

For completeness, I'd like to mention Path.Combine , which does the opposite:

var dirAndFile = Path.Combine(@"E:\test\img", "sig.jpg");
// no more checking for trailing slashes, hooray!

To create the directory, you can use Directory.Create . Note that it is not necessary to check if the directory exists first .

Another solution can be :

FileInfo f = new FileInfo(@"E:\test\img\sig.jpg");
if (f.Exists)
{
    string dirName= f.DirectoryName;
}

You can try this code to find the directory name. System.IO.FileInfo fi = new System.IO.FileInfo(@"E:\\test\\img\\sig.jpg"); string dirname = fi.DirectoryName;

and to create the directory Directory.CreateDirectory(dirname );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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