473,789 Members | 2,544 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Correctly identifying FileInfo vs. DirectoryInfo entries

I am having the following problem: I create a FileSystemWatch er and
wait for events. When the event does happen I refresh a
FileSystemInfo list and set properties accordingly (IsFile, IsDir,
ReadOnly, etc.). The problem I'm having is in identifying when a
FileSystemInfo entry is a FileInfo or a DirectoryInfo type. I get the
rare, and yet oddly common, "setup.inf" file that for some
inexplicable reason passes the standard (FileSystemInfo .Attributes &
FileAttributes. Directory) test but throws an Illegal Cast exception
when cast to a DirectoryInfo object.

How can I reliably determine the specific type from a FileSystemInfo
object?

Tom Padilla
Dec 6 '07 #1
5 6147
Tom P. <pa***********@ gmail.comwrote:
I am having the following problem: I create a FileSystemWatch er and
wait for events. When the event does happen I refresh a
FileSystemInfo list and set properties accordingly (IsFile, IsDir,
ReadOnly, etc.). The problem I'm having is in identifying when a
FileSystemInfo entry is a FileInfo or a DirectoryInfo type. I get the
rare, and yet oddly common, "setup.inf" file that for some
inexplicable reason passes the standard (FileSystemInfo .Attributes &
FileAttributes. Directory) test but throws an Illegal Cast exception
when cast to a DirectoryInfo object.

How can I reliably determine the specific type from a FileSystemInfo
object?
if (info is FileInfo)
{
....
}

or

FileInfo file = info as file;
if (file != null)
{
....
}

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Dec 6 '07 #2
On Thu, 06 Dec 2007 12:36:10 -0800, Tom P. <pa***********@ gmail.comwrote:
I am having the following problem: I create a FileSystemWatch er and
wait for events. When the event does happen I refresh a
FileSystemInfo list and set properties accordingly (IsFile, IsDir,
ReadOnly, etc.). The problem I'm having is in identifying when a
FileSystemInfo entry is a FileInfo or a DirectoryInfo type. I get the
rare, and yet oddly common, "setup.inf" file that for some
inexplicable reason passes the standard (FileSystemInfo .Attributes &
FileAttributes. Directory) test but throws an Illegal Cast exception
when cast to a DirectoryInfo object.

How can I reliably determine the specific type from a FileSystemInfo
object?
Well, there's always the Object.GetType( ) method. Depending on what
you're trying to do, often the C# "is" and "as" operators are useful.
"is" allows you to test whether an instance is a specific type, and "as"
is essentially a cast that returns null instead of throwing an exception
when the cast fails.

I don't really get how a file can be rare and common at the same thing.
You're also not clear about where you get the FileSystemInfo instance
from. As far as I know, this isn't something that the FileSystemWatch er
provides you (the event args return paths in strings, not FileSystemInfo
objects). So while there's a way to check the type of the instance, it
would probably make more sense to try to figure out why you get an
apparently incorrect type for the instance in the first place.

Without you having posted any code, it's pretty much impossible for anyone
to assist with that. But until you understand why the Attributes property
doesn't match the type of the instance, I think it's premature to work
around the issue. It may be that things are working as designed, but you
should make sure that's true first. It seems to me that there's a good
chance you're not maintaining your list of FileSystemInfo objects
correctly and it would be a bad idea to obscure that problem with a
workaround.

Pete
Dec 6 '07 #3
On Dec 6, 3:03 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Thu, 06 Dec 2007 12:36:10 -0800, Tom P. <padilla.he...@ gmail.comwrote:
I am having the following problem: I create a FileSystemWatch er and
wait for events. When the event does happen I refresh a
FileSystemInfo list and set properties accordingly (IsFile, IsDir,
ReadOnly, etc.). The problem I'm having is in identifying when a
FileSystemInfo entry is a FileInfo or a DirectoryInfo type. I get the
rare, and yet oddly common, "setup.inf" file that for some
inexplicable reason passes the standard (FileSystemInfo .Attributes &
FileAttributes. Directory) test but throws an Illegal Cast exception
when cast to a DirectoryInfo object.
How can I reliably determine the specific type from a FileSystemInfo
object?

Well, there's always the Object.GetType( ) method. Depending on what
you're trying to do, often the C# "is" and "as" operators are useful.
"is" allows you to test whether an instance is a specific type, and "as"
is essentially a cast that returns null instead of throwing an exception
when the cast fails.

I don't really get how a file can be rare and common at the same thing.
You're also not clear about where you get the FileSystemInfo instance
from. As far as I know, this isn't something that the FileSystemWatch er
provides you (the event args return paths in strings, not FileSystemInfo
objects). So while there's a way to check the type of the instance, it
would probably make more sense to try to figure out why you get an
apparently incorrect type for the instance in the first place.

Without you having posted any code, it's pretty much impossible for anyone
to assist with that. But until you understand why the Attributes property
doesn't match the type of the instance, I think it's premature to work
around the issue. It may be that things are working as designed, but you
should make sure that's true first. It seems to me that there's a good
chance you're not maintaining your list of FileSystemInfo objects
correctly and it would be a bad idea to obscure that problem with a
workaround.

Pete
Fair enough.

First off the file "setup.inf" is rare in that it is only created as a
result of building an install (*.msi). But, being a developer this is
actually a common occurrence _for me_ so I keep running into this more
than your average user. It's a temporary file but the
FileSystemWatch er will see it before it gets deleted.

You are correct in asserting that FileSystemWatch er only returns a
path. I have to then do a this.Invoke() to call a method on the main
thread that refreshes the watched directory (which is stored in a
member variable so there's no need to pass it). I don't believe the
problem lies in the FileSystemWatch er (since I don't do anything but
call a Refresh() method). The following is the code snippet that I
believe is causing the conflict:

Create a DirectoryInfo for this Path
CurrentDirInfo = new DirectoryInfo(P ath);

//Get an array of all the file system objects in the directory
FileSystemInfoL ist = CurrentDirInfo. GetFileSystemIn fos();

//Loop through each object in the array...
foreach (FileSystemInfo CurrentFileSyst emInfo in FileSystemInfoL ist)
{
FileSystemListV iewItem CurrentListView Item;

//...and determine if it is a Directory (has the
FileAttributes. Directory flag)
if ((CurrentFileSy stemInfo.Attrib utes & FileAttributes. Directory)
== FileAttributes. Directory) //[TAG01]
{
CurrentListView Item = new
FileSystemListV iewItem((Direct oryInfo)Current FileSystemInfo) ; //
[TAG02]
}
else
{
CurrentListView Item = new
FileSystemListV iewItem((FileIn fo)CurrentFileS ystemInfo);
}

this.Items.Add( CurrentListView Item);
}

The if at [TAG01] was copied directly from MSDN.

I've used Console.WriteLi ne to print out the FileAttributes flags and
the file "setup.inf" writes a "-1" rather than "Directory" but the
"if" statement above still evaluates to "true" for the file. When the
code at [TAG01] evaluates "true" then the code at [TAG02] obviously
throws an Illegal Cast exception when it casts the "setup.inf" file to
a DirectoryInfo.

I could get a list of DirectoryInfo objects and then a second list of
FileInfo objects but this seemed more efficient at the time.

It looks as if the "is" keyword is what I need here. A simple test of
whether the particular item is a DirectoryInfo object or a FileInfo
object. Then I don't have to rely on the FileAttributes flags at all.

Thanks,
Tom Padilla
Dec 6 '07 #4
[Snip all context]

Just because of the subject of the thread, I thought I would post this. Even
though it's not really revant to the discussion....

There is actually a 3rd very similar Info class called "FileVersionInf o",
and is found in System.Diagnost ics.

For years now, i've been making Win32 calls to get this. Why on earth isn't
it in the normal File Class?

--
Chris Mullins
Dec 6 '07 #5
On Thu, 06 Dec 2007 13:59:11 -0800, Tom P. <pa***********@ gmail.comwrote:
[...]
It looks as if the "is" keyword is what I need here. A simple test of
whether the particular item is a DirectoryInfo object or a FileInfo
object. Then I don't have to rely on the FileAttributes flags at all.
I guess. For that matter, it's not clear to me why the
FileSystemListV iewItem class doesn't just take a FileSystemInfo reference
in a constructor and then handle that logic (whether checking the type or
the Attributes property) inside the constructor, rather than forcing each
client of the class to perform the test.

Still, I would want to know why you're getting -1 as the Attributes
property value for that file. I don't have an answer to that, but it
seems wrong to me. It looks more like an error condition or something,
since it's not a valid value for the enumeration at all.

It's true that if the real issue is being able to cast the object to the
right thing, the type-checking operators are a very direct and reliable
way to do that. But I would be concerned about using a FileSystemInfo
object that has an invalid value for one of its properties. That could
lead to problems in the future. I almost wonder if you should try to
reacquire the FileSystemInfo object for objects that have that property
set to -1, and/or just ignore them as invalid data.

Pete
Dec 7 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6163
by: David | last post by:
I know that identifying the user IP address with HTTP_SERVER_VARS; is reliant on the browser agent but I have stumpled upon the following code which I have tried to understand but failed! // // Obtain and encode users IP //
2
10058
by: David Turner | last post by:
I have created an ASP.NET page that uses the System.IO.DirectoryInfo.GetFiles() method to get a list of files in a specific directory on our web server. (I simply use this list to build some javascript code). I'm never opening the files or accessing them in any other way. Problem is, that once this ASP.NET page is accessed, we can then no longer delete or rename any of the files in that directory unless we restart IIS. If I try and...
4
6013
by: G. Richard Bellamy | last post by:
I'm trying to unset the Encrypted attribute on all the files in a path. The attribute is not getting set. What am I doing wrong? Perhaps there's another newsgroup I can send this to? Here's the code: ============================================= using System;
2
2513
by: John Bowman | last post by:
Hi All, ..NET 1.1... I'm wondering if there is any approach more convenient to get a list of FileInfo objects than the following. For example, if I wanted to get 1 list of all the Exe's and all the Dll's and all the Txt's in a folder, if appears I need to do something like the following: ArrayList InterestingFiles = new ArrayList(); DirectoryInfo di = new DirectoryInfo(@"C:\My Folder");
1
1503
by: Antonio | last post by:
Good morning, I've the following file system : C: -> HTML -> Aziende -> Azienda_1 -> a.jpg -> Azienda_2 -> a.jpg ... -> Azienda_N -> a.jpg my desire is to create an array of fileinfo containing the a.jpg , a.jpg , ... , a.jpg
10
5898
by: Michael Murphy | last post by:
Hi, I have a Windows VB.Net app in which I need to keep files in one folder in sync with files in another folder. I have pasted the code below. Can anyone tell me why I end up with a folder with all the file names correct, but the length of each file is zero. Thanks for your help. Michael Public Function SyncFiles() As Integer Dim CopyToPath As String Dim CopyFromPath As String Dim CopyToPathFileInfo As FileInfo Dim...
1
1411
by: R. Harris | last post by:
Here is what I'm trying to accomplish: When my form loads it looks at a specific directory for a list of its files and populates a combo box. Dim a As New IO.DirectoryInfo("c:\dir") Dim b As IO.FileInfo() = a.GetFiles() Dim c As IO.FileInfo For Each c In b comboBox1.Items.Add(c)
3
2172
by: rn5a | last post by:
To work with files, when should one use the File class & when should one use the FileInfo class? Similarly, to work with directories, when should one use the Directory class & when should one use the DirectoryInfo class?
0
2693
by: dolphinearth | last post by:
Hi. I have a strange problem around DirectoryInfo and FileInfo of C# (c- sharp). I have a File Watcher which automattically imports files from a network drive to a directory on the local machine. Here is the code I used: DirectoryInfo dir = new DirectoryInfo(SAPImportPath); FileInfo fileList = dir.GetFiles("*.txt");
0
9663
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10195
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5415
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2906
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.