Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / February 2008

Tip: Looking for answers? Try searching our database.

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

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Tom P. - 21 Feb 2008 21:50 GMT
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
Jon Skeet [C# MVP] - 21 Feb 2008 22:01 GMT
> I looked and the last guy to ask this was in 2005 and he didn't get an
> answer either.
[quoted text clipped - 10 lines]
> 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.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Tom P. - 21 Feb 2008 23:16 GMT
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.
Homer J. Simpson - 21 Feb 2008 23:24 GMT
> 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.
Ben Voigt [C++ MVP] - 21 Feb 2008 23:24 GMT
> 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.
Tom P. - 22 Feb 2008 14:29 GMT
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
Jon Skeet [C# MVP] - 21 Feb 2008 23:28 GMT
> 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?

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Mufaka - 22 Feb 2008 00:35 GMT
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?

> 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
[quoted text clipped - 4 lines]
>
> Tom P.
Roger Frost - 22 Feb 2008 03:55 GMT
> 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
[quoted text clipped - 4 lines]
>
> 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.

Signature

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>

Peter Duniho - 22 Feb 2008 04:13 GMT
> 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
Roger Frost - 22 Feb 2008 04:44 GMT
>> Lets back up a minute, has everyone actually tested this?
>>
[quoted text clipped - 14 lines]
>
> 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
[quoted text clipped - 4 lines]
>
> 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. :)
Peter Duniho - 22 Feb 2008 05:09 GMT
> 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:
>
[quoted text clipped - 12 lines]
> "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
Roger Frost - 22 Feb 2008 05:36 GMT
>> 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
[quoted text clipped - 4 lines]
>
> 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.

>> 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.  :)

Yeah I agree, that idea was just plain silly.

>> 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. :)
[quoted text clipped - 5 lines]
>
> Pete

Why thank you, I will ponder the problem more.

Signature

Roger Frost
"Logic Is Syntax Independent"

Scott Roberts - 22 Feb 2008 07:36 GMT
> If something doesn't exist it simply doesn't exist.

How very existentialist of you.
Homer J. Simpson - 22 Feb 2008 20:01 GMT
>> If something doesn't exist it simply doesn't exist.
>
> How very existentialist of you.

Non-existentialist, actually...I think...therefore, I am...or maybe not.
*poof!*
Scott Roberts - 22 Feb 2008 20:29 GMT
>>> If something doesn't exist it simply doesn't exist.
>>
>> How very existentialist of you.
>
> Non-existentialist, actually...I think...therefore, I am...or maybe not.
> *poof!*

Someone like Descartes (who turned the phrase "I think, therefore I am")
would say that just because you perceive the file/directory to exist doesn't
mean that it actually *does* exist. Similarly, the fact that you don't
perceive it to exist does not necessarily mean that it does not.

To state definitively that something exists (or doesn't exist) is decidedly
Existentialist. :)
Kevin Spencer - 22 Feb 2008 12:13 GMT
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";
}

Signature

HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP

> 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
[quoted text clipped - 4 lines]
>
> Tom P.
Alcides - 21 Feb 2008 22:02 GMT
Try using Directory.Exists.

Alcides Schulz
http://alsql.blogspot.com
Alcides - 21 Feb 2008 22:04 GMT
For example: Console.WriteLine(System.IO.Directory.Exists("C:/Temp"));
Kelly Herald - 22 Feb 2008 18:20 GMT
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!");
}

>I looked and the last guy to ask this was in 2005 and he didn't get an
> answer either.
[quoted text clipped - 14 lines]
>
> Tom Padilla
Jon Skeet [C# MVP] - 22 Feb 2008 18:29 GMT
> This is actually very simple. Here's an example.
>
[quoted text clipped - 11 lines]
>  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?

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Kelly Herald - 22 Feb 2008 19:58 GMT
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.

>> This is actually very simple. Here's an example.
>>
[quoted text clipped - 15 lines]
> Um, if you're already calling Directory.Exists() and File.Exists(), why
> bother fetching the attributes?
jehugaleahsa@gmail.com - 23 Feb 2008 04:21 GMT
> I looked and the last guy to ask this was in 2005 and he didn't get an
> answer either.
[quoted text clipped - 14 lines]
>
> Tom Padilla

...

if (Directory.Exists(path))
{
   // it HAS to be a directory; files are NOT directories
}
else if (File.Exists(path))
{
  // we know it is a file since directories were already handled.
}

What's seems to be the confusion?

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.