1

I want to check if each item in a directory is of type file or a folder in using C#. I want to write something like the code below. But IsInstanceOfType(FileInfo)and IsInstanceOfType(DirectoryInfo) is not allowed in C#.

    DirectoryInfo dirPrograms = new DirectoryInfo(folderPath);                     
    foreach(var dir in dirPrograms.EnumerateFileSystemInfos())
        {
            if (dir.GetType().IsInstanceOfType(FileInfo))
                  //do something
            elseif (dir.GetType().IsInstanceOfType(DirectoryInfo))
                //do something
        }
Soumya
  • 323
  • 1
  • 5
  • 16
  • Does this answer your question? [Better way to check if a Path is a File or a Directory?](https://stackoverflow.com/questions/1395205/better-way-to-check-if-a-path-is-a-file-or-a-directory) – BurnsBA Sep 27 '22 at 13:48

4 Answers4

2

You can use the is operator to check whether an object can be converted to a specific type:

if (dir is FileInfo)
  // do something
else (dir is DirectoryInfo)
  // Do something
Markus
  • 20,838
  • 4
  • 31
  • 55
0

Although you can solve this using the is operator, I'd rather avoid using reflection and check it by inspecting the Attributes property like this:

foreach (var dir in dirPrograms.EnumerateFileSystemInfos())
{
    if (dir.Attributes.HasFlag(FileAttributes.Directory))
    {
        // It's a dir
    }
    else
    {
        // It's a file
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

You do not have permission to read all the folders. So you need to recursively go through folders and continue when you get an exception like code below :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace SAveDirectoriesXml
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string FOLDER = @"c:\temp";
        static XmlWriter writer = null;
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            writer = XmlWriter.Create(FILENAME, settings);
            writer.WriteStartDocument(true);

            DirectoryInfo info = new DirectoryInfo(FOLDER);
            WriteTree(info);
            
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
            Console.WriteLine("Enter Return");
            Console.ReadLine();

        }
        static long WriteTree(DirectoryInfo info)
        {
            long size = 0;
            writer.WriteStartElement("Folder");
            try
            {
                writer.WriteAttributeString("name", info.Name);
                writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
                writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
                writer.WriteAttributeString("date", info.LastWriteTime.ToString());
             

                foreach (DirectoryInfo childInfo in info.GetDirectories())
                {
                    size += WriteTree(childInfo);
                }
                
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            FileInfo[] fileInfo = null;
            try
            {
                fileInfo = info.GetFiles();
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error",errorMsg);
            }

            if (fileInfo != null)
            {
                foreach (FileInfo finfo in fileInfo)
                {
                    try
                    {
                        writer.WriteStartElement("File");
                        writer.WriteAttributeString("name", finfo.Name);
                        writer.WriteAttributeString("size", finfo.Length.ToString());
                        writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                        writer.WriteEndElement();
                        size += finfo.Length;
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                        Console.WriteLine(errorMsg);
                        writer.WriteElementString("Error", errorMsg);
                    }
                }
            }

            writer.WriteElementString("size", size.ToString());
            writer.WriteEndElement();
            return size;

        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
0

you could also use the FileSystemInfo.FullPath and then the Directory and File classes to check if the file or folder exists.

So in your foreach loop it would be something like this.

if (Directory.Exists(dir.FullPath))
     // do something it its a folder
elseif (File.Exists(dir.FullPath))
     // do something if its a file, shouldn't have to check this condition really but it wouldn't hurt to be safe
frankM_DN
  • 365
  • 7