How do I tell if a string is a file or a directory?

  • Thread starter Thread starter Tom P.
  • Start date Start date
T

Tom P.

I looked and the last guy to ask this was in 2005 and he didn't get an
answer either.

I have an application that is handling both files and directories
(like a file manager). I need to be able to determine if the string
passed in is a file or a directory.

It's not good enough to use File.Exists() since that will simply tell
me the file is not a real file on the harddrive, not whether it
properly represents a file. Also, checking the FileInfo.Extension
doesn't help anymore because files don't require extensions. I've
tried FileInfo.Length (get FileNotFoundException which is the same as
Exists above). I've tried everything I can think of and I can't come
up with anything.

Thanks for any help you can give.

Tom Padilla
 
Tom P. said:
I looked and the last guy to ask this was in 2005 and he didn't get an
answer either.

I have an application that is handling both files and directories
(like a file manager). I need to be able to determine if the string
passed in is a file or a directory.

It's not good enough to use File.Exists() since that will simply tell
me the file is not a real file on the harddrive, not whether it
properly represents a file. Also, checking the FileInfo.Extension
doesn't help anymore because files don't require extensions. I've
tried FileInfo.Length (get FileNotFoundException which is the same as
Exists above). I've tried everything I can think of and I can't come
up with anything.

Try File.Exists in combination with Directory.Exists.
 
All of the *.Exists methods tell me is if the string is currently a
real File System Object, not if it represents a possible File or a
possible Directory.

Given the string "C:\RandomDir\RandomName" how do I tell if that could
be referring to a file (without an extension) or a directory?

Tom P.
 
All of the *.Exists methods tell me is if the string is currently a
real File System Object, not if it represents a possible File or a
possible Directory.

Given the string "C:\RandomDir\RandomName" how do I tell if that could
be referring to a file (without an extension) or a directory?

Off the top of my head...I think there's some FileInfo structure with an
..Attributes member. I'm pretty sure the flag you're looking for is in
there.
 
Tom said:
All of the *.Exists methods tell me is if the string is currently a
real File System Object, not if it represents a possible File or a
possible Directory.

Given the string "C:\RandomDir\RandomName" how do I tell if that could
be referring to a file (without an extension) or a directory?

Do you have any example where the result is one or the other? Because I
think the answer can only be "both" or "neither", valid directory names are
valid file names.

The only thing I can think of is that a name ending in a slash (front or
back) can only be a directory... at least on Windows. Unix you'd test for
front-slash (only), and Mac before OS X for colon.
 
Tom P. said:
All of the *.Exists methods tell me is if the string is currently a
real File System Object, not if it represents a possible File or a
possible Directory.

Given the string "C:\RandomDir\RandomName" how do I tell if that could
be referring to a file (without an extension) or a directory?

You can't. It could be either. It's like asking whether the number 40
represents a temperature in Celsius or Fahrenheit.

Put it this way:
o Could you create a file c:\RandomDir\RandomName? Yes.
o Could you create a directory c:\RandomDir\randomName? Yes.

So what answer would you want to be given?
 
The application(s) responsible for passing in the strings is going to
also have to tell you what the path is for.

If you can't require that, you will have to use fuzzy logic to determine
this. ie: retrieve all the strings and determine if a given path is a
root of another path. If so its a directory otherwise its a file (or an
empty directory :/)

What is your application doing with these paths if you don't have access
to the file system where they belong?
 
Tom P. said:
All of the *.Exists methods tell me is if the string is currently a
real File System Object, not if it represents a possible File or a
possible Directory.

Given the string "C:\RandomDir\RandomName" how do I tell if that could
be referring to a file (without an extension) or a directory?

Tom P.

Lets back up a minute, has everyone actually tested this?

Try running the simple console application that follows, I get the indicated
values on my system (Win XP SP 2), seem right to me.

Maybe I'm just missing a major point.

Please forgive the length, just trying to be thorough.


--
Roger Frost
"Logic Is Syntax Independent"

<begin sample app>

using System;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

//Running on Windows XP SP2

//Visual C# 2008 Express Edition
//.NET 3.5

//In drive D:

//New > Text Document
//Rename to 'temp' (no extension)

//New > Text Document
//Rename to 'temp.file'

//New > Folder
//Rename to 'temp2'

//New > Folder
//Rename to 'temp.dir'

//'NONE' Is known to not exist in the file system

//class System.IO.File
Console.WriteLine("File.Exists(\"D:\\\\temp\"): " +
File.Exists("D:\\temp")); //True
Console.WriteLine("File.Exists(\"D:\\\\temp.file\"): " +
File.Exists("D:\\temp.file")); //True
Console.WriteLine("File.Exists(\"D:\\\\temp2\"): " +
File.Exists("D:\\temp2")); //False
Console.WriteLine("File.Exists(\"D:\\\\temp.dir\"): " +
File.Exists("D:\\temp.dir")); //False
Console.WriteLine("File.Exists(\"D:\\\\NONE\"): " +
File.Exists("D:\\NONE")); //False

Console.WriteLine();

//class System.IO.Directory
Console.WriteLine("Directory.Exists(\"D:\\\\temp\"): " +
Directory.Exists("D:\\temp")); //False
Console.WriteLine("Directory.Exists(\"D:\\\\temp.file\"): " +
Directory.Exists("D:\\temp.file")); //False
Console.WriteLine("Directory.Exists(\"D:\\\\temp2\"): " +
Directory.Exists("D:\\temp2")); //True
Console.WriteLine("Directory.Exists(\"D:\\\\temp.dir\"): " +
Directory.Exists("D:\\temp.dir")); //True
Console.WriteLine("Directory.Exists(\"D:\\\\NONE\"): " +
Directory.Exists("D:\\NONE")); //False

Console.WriteLine();

//Test it in Principle

string path = "D:\\temp";

if (File.Exists(path) == true)
{
Console.WriteLine(path + " is a file");
}
else if (Directory.Exists(path) == true)
{
Console.WriteLine(path + " is a directory");
}
else
{
Console.WriteLine(path + " does not exist");
}

//My Output: "D:\temp is a file"

System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

}
}
}

<end sample app>
 
Lets back up a minute, has everyone actually tested this?

Try running the simple console application that follows, I get the
indicated values on my system (Win XP SP 2), seem right to me.

Maybe I'm just missing a major point.

You seem to be missing the point that everyone else is talking about the
condition where the name being tested does not exist either as a file or a
directory.

Your code tests an existing file, and so of course can tell the difference
between a file and a directory. Delete the file "temp" and then tell us
if it can still tell you whether the path represents a file or a
directory. Unless your system is using some alien technology or
something, it won't be able to.

Pete
 
Peter Duniho said:
You seem to be missing the point that everyone else is talking about the
condition where the name being tested does not exist either as a file or a
directory.

Your code tests an existing file, and so of course can tell the difference
between a file and a directory. Delete the file "temp" and then tell us
if it can still tell you whether the path represents a file or a
directory. Unless your system is using some alien technology or
something, it won't be able to.

Pete

If something doesn't exist it simply doesn't exist.

I could check to see if the deleted item temp _was_ a file or a directory if
sufficient information is still available on the hard drive, but that’s
beyond the point.

Why would we need to know if something is a file or directory if something
is not there anyhow?

I was targeting the post:
All of the *.Exists methods tell me is if the string is currently a
real File System Object, not if it represents a possible File or a
possible Directory.

Given the string "C:\RandomDir\RandomName" how do I tell if that could
be referring to a file (without an extension) or a directory?

Tom P.

I see your point "...not if it represents a possible File or a possible
Directory."

"Possible" being the operative word I guess, but again, why would we need
to? If its not there, who cares what it could possibly be?

It could possibly be a file, a directory or an elephant. I would prefer it
to possibly be a cold beer, but if it doesn't exist then I'm still thirsty.

On the other hand, I can choose to call it a cold beer, and no one can prove
that I'm wrong... without "alien technology or something."

But if we all want a cold beer, then why argue? Lets just make up more NULL
cold beers and hope we eventually get to drink one.

Thanks for pointing this out to me Peter, I think I'll stay out of this
thread for the remainder of it's already overly-extended life span. :)
 
If something doesn't exist it simply doesn't exist.

Yes, exactly. I think you have it now. :)
I could check to see if the deleted item temp _was_ a file or a
directory if sufficient information is still available on the hard
drive, but that’s beyond the point.

Very much, yes.
Why would we need to know if something is a file or directory if
something is not there anyhow?

I can only hypothesize. The OP didn't say (or I didn't notice if he did)
why he wants to make this determination.

But the fact is, that's what he appears to want to do.
I was targeting the post:


I see your point "...not if it represents a possible File or a possible
Directory."

"Possible" being the operative word I guess, but again, why would we
need to? If its not there, who cares what it could possibly be?

I don't know. I didn't think we needed to know that in order to answer
the question. I was probably wrong about that, in fact. After all, since
the answer is "you can't do that", a better answer would take into account
whatever it is the OP is really trying to do and help him with _taht_.
It could possibly be a file, a directory or an elephant. I would prefer
it to possibly be a cold beer, but if it doesn't exist then I'm still
thirsty.

Well, at least a file or directory can in fact be retrieved, at least in a
virtual sense, via the .NET API.

When you get the cold beer feature working, let me know. Sounds great.
On the other hand, I can choose to call it a cold beer, and no one can
prove that I'm wrong... without "alien technology or something."

Well, perhaps that's the answer in fact. If all the OP wants to know is
whether the path is a valid filename or a valid directory, the answer is
"it's both" and no one can tell him it's neither, not until it's one or
the other.
But if we all want a cold beer, then why argue? Lets just make up more
NULL cold beers and hope we eventually get to drink one.

I'd rather wait until you get the kinks worked out of that feature. I
prefer non-null beers. :)
Thanks for pointing this out to me Peter, I think I'll stay out of this
thread for the remainder of it's already overly-extended life span. :)

Well, once you got back on track, it seems to me you contributed as much
useful thought to the thread as anyone else. You can stay out of the
thread if you want, but if you come up with other good ideas, you might
share them anyway.

Pete
 
Peter Duniho said:
Well, at least a file or directory can in fact be retrieved, at least in a
virtual sense, via the .NET API.

When you get the cold beer feature working, let me know. Sounds great.

My girlfriend will do that if I ask nicely. I do feel, however, that if I
try to call her via the API, she will throw an Exception and our
relationship will Lock possibly resulting in a Fatal system crash.

I'd rather wait until you get the kinks worked out of that feature. I
prefer non-null beers. :)

Yeah I agree, that idea was just plain silly.
Well, once you got back on track, it seems to me you contributed as much
useful thought to the thread as anyone else. You can stay out of the
thread if you want, but if you come up with other good ideas, you might
share them anyway.

Pete

Why thank you, I will ponder the problem more.
 
Tom,

The System.IO.File.Exists method will tell you if a FILE with the path
specified exists. If it returns true, the path specifies a file. If it
returns false, the path either does not exist at all, or it is a directory.
You can then determine which of these two options is true by using
System.IO.Directory.Exists.

public string FileOrDirectory(string path)
{
if (File.Exists(path) return "file";
if (Directory.Exists(path) return "directory";
return "neither";
}

--
HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP
 
First off, for what it's worth, I'm writing a side-by-side file
manager and it's the drag/drop from Windows File Manager that was
getting me mixed up.


Do you have any example where the result is one or the other? Because I
think the answer can only be "both" or "neither", valid directory names are
valid file names.

Thank you for that. Also, thanks Peter, Roger, and Jon.

The problem is this: the OnDragDrop handler has event args that
encapsulate the "objects" that were dropped on your file manager
object. When you separate everything out you end up with an array of
strings that is the "things" that were dropped. I was looking for a
way to determine what those "things" could be. I was thinking that
these strings are not coming from my application so I can't attach any
significance to them, I have to figure out what they are all by
myself.

Well, the conversation has helped me realize that if the string
represents an actual file or directory I'll get a "true" from one of
the Exists methods... if the string is not an actual file or directory
- What do I care what it could be? A little more evaluation of the
situation led me to the conclusion that the only you can do with a
string that doesn't exist is create it. Since my app isn't into
creating content everything I deal with will be real (or an
Exception).

Thank you guys so very much for the help. This is just one of the
drawbacks to designing by yourself.

Tom Padilla
 
This is actually very simple. Here's an example.


String fileName = @"D:\ISOs";
System.IO.FileAttributes fa = System.IO.File.Exists(fileName) |
System.IO.Directory.Exists(fileName) ?
System.IO.File.GetAttributes(fileName) : 0;
// returns 0 if the file doesn't exist otherwise the returned value is the
file/directory attributes mask
if ((fa & System.IO.FileAttributes.Directory) != 0)
{
System.Diagnostics.Debug.WriteLine("The string is a directory!");
}else
{
System.Diagnostics.Debug.WriteLine("The string is a file!");
}
 
Kelly Herald said:
This is actually very simple. Here's an example.


String fileName = @"D:\ISOs";
System.IO.FileAttributes fa = System.IO.File.Exists(fileName) |
System.IO.Directory.Exists(fileName) ?
System.IO.File.GetAttributes(fileName) : 0;
// returns 0 if the file doesn't exist otherwise the returned value is the
file/directory attributes mask
if ((fa & System.IO.FileAttributes.Directory) != 0)
{
System.Diagnostics.Debug.WriteLine("The string is a directory!");
}else
{
System.Diagnostics.Debug.WriteLine("The string is a file!");
}

Um, if you're already calling Directory.Exists() and File.Exists(), why
bother fetching the attributes?
 
Yeah, you're right. I saw that after I posted. <smacks forehead>

Since I program mostly in C++/MFC I'm just used to using the Win32 API
GetFileAttributes which returns INVALID_FILE_ATTRIBUTES if the
file/directory doesn't exist or testing the return value to see if the value
has the FILE_ATTRIBUTE_DIRECTORY bit set. It would have been nice if
Microsoft would have made the System.IO.File.GetAttributes function behave
the same as the Win32 API.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top