Germstorm
Germstorm

Reputation: 9849

Decide if path is file or directory (the path does not exist on disk)

I am trying to extract the directory from a path that may or may not contain the file name. The problem is that when I am trying to get the directory name of a path that is already a directory, the Path.GetDirectoryName() returns the upper level of that dir. The path is loaded from the database so I cannot check the file attributes.

Ex. Path.GetDirectoryName("D:\Work\Project\Sources\trunk\Project2\bin\Debug") returns "D:\Work\Project\Sources\trunk\Project2\bin\"

I was thinking of a simple algorithm, that checks if the path contains the "." character; if yes, then we are dealing with a path that contains the file name. Unfortunately the directory names can also contain the "." character.

I know that there is no perfect solution for this issue but what is the next best thing?

There is already a Stackoverflow question about the issue but it assumes that the file or directory already exists.

Upvotes: 0

Views: 478

Answers (2)

Tamir Dresher
Tamir Dresher

Reputation: 194

for your scenario and if your cases really involve only a "file.ext" format, then the following regex will answer ehat you need

^(.*/)([^/]*)$

Upvotes: 1

ken2k
ken2k

Reputation: 49013

If your directory or file doesn't exist, there is no way to know if it's a file or a directory.

In your example D:\Work\Project\Sources\trunk\Project2\bin\Debug, there could be a file named Debug (without extension) in the bin directory.

Another example: D:\Work\Project\Sources\trunk\Project2\bin\Debug\file.exe, there could be a directory named file.exe which is a sub-dir of Debug...

Upvotes: 3

Related Questions