0

I'm trying to write some code to find a specific file (e.g. myfile.exe) I found various code snippets, but none work when you are scanning the root of the drives. e.g.

private string Findfile(string myname)
        {
            var files = new List<string>();

            foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
            {
                try
                {
                    Updatestatus("Searching " + d.RootDirectory.FullName);
                    files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, myname, SearchOption.AllDirectories));
                }
                catch { }
            }
            if (files.Count == 0) { return "Not Found"; } else {
                return files.First(); }
        }

When I try and trap any errors (it throws an error if it tries to scan the recycle bin for example) as above, the entire drive is skipped. Numerous other examples on stack exchange suffer from the same problem of throwing an exception if starting at the root level of a drive and scanning recusivley.

Jimmyeao
  • 15
  • 1
  • 6
  • Does this answer your question? [How can I get all files in a directory skipping unauthorized files?](https://stackoverflow.com/questions/65542300/how-can-i-get-all-files-in-a-directory-skipping-unauthorized-files) –  Nov 22 '22 at 11:25
  • That code doesn't even compile as is; there is not enough info there in the answer for me to know what to include and is incomplete :( – Jimmyeao Nov 22 '22 at 11:46
  • The linked answer is _not_ incomplete. It tells you all you need to know. Don't just blindy try to copy'n'paste some code into your project; doing so rarely ends well. Read the text of the accepted answer to the question i linked to. –  Nov 22 '22 at 12:20
  • I beg to disagree, it is an incomplete answer is therefore not of much use. The linked documentation adds little value to the answer, and crucially, the example given does not work as it is presented; this example throws errors (EnumerationOptions does not contain a definition for 'IgnoreInaccessible) which is far from a blind copy paste issue. It suggest more information is required to understand the issue which is not given in the context of the answer. I appreciate you trying to help with the link, but many of the existing examples on here do not work and are too brief in explanation. – Jimmyeao Nov 22 '22 at 12:55

1 Answers1

0

GetFiles will abort as soon as you get an exception (usually due to not having read permission). Best way is do it recursive 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
  • I'm not sure from that example how it relates? I'm pretty new to C# – Jimmyeao Nov 22 '22 at 12:08
  • 1
    The code gets all files info in the folder selected at top of code and puts info into an xml file. Instead of using SearchOption.AllDirectories (recursively getting the files/folders) my code does one folder at a time recursively. The exception handlers are inside the FOR loops so when an exception occurs the code continues. Your code when an exception occurs just stops at first exception. – jdweng Nov 22 '22 at 12:54
  • ok, I think I understand - your example goes 1 level deep under the specified folder, so from there I am trying to then search recursively for the file (using directory.getfiles, which I suspect is the wrong way to go ), with its own try..catch statement, but bombs out of a folder if it hits a problem with any of the subfolders in it – Jimmyeao Nov 22 '22 at 13:38
  • Code goes more than one level. It is recursive and will search entire folder. Code will also tell which folders/files fail. – jdweng Nov 22 '22 at 13:59