xxbbcc
xxbbcc

Reputation: 17327

Possible to tell if a path represents a file or folder name in C#/.NET 2.0?

I know several similar questions were asked in the past and I also know I could use Directory.Exists() or File.Exists() or to check the file system using API calls but I'm trying to make this decision simply based on an input string.

public bool ValidateOutputFilename ( string sPath )
{
    // check if sPath is actually a filename
}

My guess is that it's not possible because something that looks like a folder name (no extension but no trailing \) may actually be a file (for example C:\A\B\C may represent a file or a folder and vice versa).

The reason I want to avoid a file system check is because the path may / may not exist and sPath may represent a network location in which case the file system query will be slow.

I'm hoping that someone can recommend an idea I haven't already considered.

Upvotes: 0

Views: 254

Answers (2)

Steve
Steve

Reputation: 216263

I think you can't avoid a file system call.
Only the file system knows for sure.
As you have said, a simple, well formatted, string is unidentifiable as a path or file.

A way to answer to your question is through the File.GetAttributes method.
It returns a FileAttributes enum value that can be tested with a bitwise AND to find if the Directory bit is set and is the fastest method (apart from a direct unmanaged call).

try
{
    // get the file attributes for file or directory 
    FileAttributes attr = File.GetAttributes(sPath);
    bool isDir = ((attr & FileAttributes.Directory) == FileAttributes.Directory) ? true : false;
    if (isDir == false)
       ....
    else
       ....
    }
}
catch(Exception ex)
{
    // here as an example. probably you should handle this in the calling code
    MessageBox.Show("GetAttributes", ex.Message);
}

Of course, if the file or directory represented by the path not exist you get an exception that should be handled.

As a side note: Directory.Exists or File.Exists could tell you if a file or directory exists with the specified name, but how do you call the correct one if you don't know what your path string represents? You need to call both to be sure.

Upvotes: 2

Carlos Martinez T
Carlos Martinez T

Reputation: 6528

There is no way to get more information about a file unless you physically read it. From what I understand, you want to avoid reading the file.

You have no other option but to verify extensions and trailing slashes contained in the string. But even like that, the result will never be real. For example, I just created this folder in my d:

D:\Music\file.txt

and I created this file inside:

D:\Music\file.txt\folder

Upvotes: 1

Related Questions