0

Possible Duplicate:
.NET How to check if path is a file and not a directory?

Can anyone think of a good way of telling whether a file system object path equates to a a file or a directory?

I did have the following method:

public static bool PathIsFile(this string fullPath)
{
    return (Path.GetExtension(fullPath).Length > 0);
}

But some files have no extension and some directories have a dot in their name so this is not cutting it.

Community
  • 1
  • 1
dagda1
  • 23,659
  • 54
  • 216
  • 399

5 Answers5

2

Have you checked out:

System.IO.Directory.Exists(path);

and

System.IO.File.Exists(path);

These return boolean, but I can't find out (at the moment) what errors they raise if given a file or directory respectively.

There's also the System.IO.FileInfo and System.IO.DirectoryInfo classes which should help you here.

ChrisF
  • 131,190
  • 30
  • 250
  • 321
1

There's no way of knowing just from a string analysis that something is a file or a directory, since, as you noted,

C:\WINDOWS\WhoKnowsWhatThisIs

might be either a directory or a file.

You'll have to call something like System.IO.Directory.Exists() or System.IO.File.GetAttributes() to test.

mqp
  • 67,323
  • 14
  • 92
  • 123
0

See .NET How to check if path is a file and not a directory?

Community
  • 1
  • 1
David Basarab
  • 70,191
  • 42
  • 128
  • 155
0

You have to ask the filesystem. It always knows. That is the only fool-proof way.

f1 = File(path);
bool isfile = f1.isFile();
bool isdir = f1.isDirectory();

Is an example from Java.IO.File.

Christopher
  • 8,538
  • 1
  • 31
  • 41
  • you might want to add "java" to 'Interested Tags' so you can quickly see which question is Java-related and which isn't – chakrit Jun 16 '09 at 19:22
0

Check out the isFile method. It's used here:

http://tools.devshed.com/c/a/Web-Development/C-Programming-Namespaces-and-the-Base-Classes-Part-4-File-and-Folder-Operations/

Dan Lorenc
  • 5,350
  • 1
  • 21
  • 33