Code
Code

Reputation: 39

Directory length not working

This may be a stupid question but im trying to find out how many files are in a folder and one minuite its telling me 0 and the next time its telling me 1 when there is simply no files there.

I even made a new folder called H in my documents with nothing in there at all and its still coming back 1 item. someone please explain this or even try it yourself, its hurting my head

int i = Directory.GetFiles(@"C:\Users\William\Documents\H\").Length;
        MessageBox.Show(Convert.ToString(i));

Upvotes: 2

Views: 116

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460208

So actually you get unwanted system files like thumbs.db. You can exclude them in this way:

string[] files = new DirectoryInfo(@"C:\Users\William\Documents\H\").GetFiles()
            .Where(f => !f.Attributes.HasFlag(FileAttributes.System | FileAttributes.Hidden))
            .Select(f => f.FullName)
            .ToArray();

Upvotes: 5

Brian Kraemer
Brian Kraemer

Reputation: 453

Very likely you have a hidden file that is being counted. Check for hidden files like thumbs.db or other system files that might be there.

Upvotes: 0

Rahul Vats
Rahul Vats

Reputation: 287

Have you tried this one:

System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;

Upvotes: -2

Related Questions