C
C#•2y ago
Kiel

Directory.CreateDirectory() for a file path while ignoring the filename

I have a file with full path /path/to/some/very/long/file.txt. I would like to be able to use Directory.CreateDirectory(path) to create all folders and subfolders on the way to that file, but in practice, it ends up creating a file.txt folder at the end. Is there a more elegant solution to this other than splitting my path string on / and reforming it minus the last piece?
3 Replies
Angius
Angius•2y ago
Yeah, split and join will do the trick I wonder if System.Path also has some ways to strip the file name Probably A quick and dirty solution would be
string.Join('/', path.Split('/')[..^2]
string.Join('/', path.Split('/')[..^2]
though
Jimmacle
Jimmacle•2y ago
you could also new FileInfo(filePath).DirectoryName i'm not sure if that works if the file doesn't exist though
Kiel
KielOP•2y ago
Actually, I found Path.GetDirectoryName("/very/long/path/to/some/file.txt"), which returns /very/long/path/to/some Was looking in the wrong place I guess 😄
Want results from more Discord servers?
Add your server