-1

I want to get all files and folders in Drive C. In fact, I want a list of all the files on the drive. All the files along with their path. I use this code .but encounters an error.

static void Main(string[] args)
    {
       
        System.IO.DriveInfo di = new System.IO.DriveInfo(@"C:\");
        System.IO.DirectoryInfo dirInfo = di.RootDirectory;

        System.IO.FileInfo[] fileNames = dirInfo.GetFiles("*.*");
        System.IO.DirectoryInfo[] dirInfos = dirInfo.GetDirectories("*.*");

        foreach (System.IO.DirectoryInfo d in dirInfos)
        {
            string[] filePaths = Directory.GetFiles(d.FullName, "*.*", 
            SearchOption.AllDirectories);
        }
    }

enter image description here

marandiiii
  • 21
  • 10
  • Does this answer your question? [Why is access to the path denied?](https://stackoverflow.com/questions/8821410/why-is-access-to-the-path-denied) – panoskarajohn Dec 26 '20 at 08:51
  • True, but I think that post did not provide a complete and accurate answer to solve this problem. – marandiiii Dec 26 '20 at 08:55
  • 1
    Try some suggestions from the other post. I do not think someone is going to be able to help you. See if you have any antivirus. See the permissions. The post provides a lot of useful information. I think that is it left without an answer due to the fact there is not one reasoning behind it. – panoskarajohn Dec 26 '20 at 09:32
  • 2
    In case it's available, in .Net 5 both `Directory` and `DirectoryInfo` classes support a new [EnumerationOption](https://learn.microsoft.com/en-us/dotnet/api/system.io.enumerationoptions) argument that can handle [Inaccessible Paths or Files](https://learn.microsoft.com/en-us/dotnet/api/system.io.enumerationoptions.ignoreinaccessible), Special Directories and have extended match properties. – Jimi Dec 26 '20 at 11:17
  • @Jimi, I could not find an example of this. Can you explain more? – marandiiii Dec 26 '20 at 12:34
  • While enumerating paths and files, you will **always** encounter (no matter how much elevated your application is running) some that you cannot access. Plus Reparse Points, Junction Points and such classes of NTFS links. Also, Paths or Files which have exclusive access (specific Users or Services). So, you always need to handle the exception when parsing directory structures, no matter what the starting point of the enumeration is. The new Directory and Files enumerations provide means to skip Path and Files when accessing these would generate an access violation exception. See the Docs. – Jimi Dec 26 '20 at 14:10

2 Answers2

0

You can simply exclude directories that you can't access by searching them one by one and surrounding all of the searches with a try-catch block. Here is an example:

Console.WriteLine("Input search pattern (or empty to search all):");
        string pattern = Console.ReadLine();
        if (pattern == "")
        {
            pattern = "*";
        }
        List<string> allDirectories = new List<string>{ @"C:\" });
        Stack<string> directories = new Stack<string>(allDirectories);
        List<string[]> allFiles = new List<string[]>();
        while (directories.Count > 0)
        {
            try
            {
                Console.WriteLine("Searching " + directories.Peek() + " for " + pattern);
                foreach (string dir in Directory.GetDirectories(directories.Pop()))
                {
                    directories.Push(dir);
                    allDirectories.Add(dir);
                    try
                    {
                        allFiles.Add(Directory.GetFiles(dir, pattern, SearchOption.TopDirectoryOnly));
                    }
                    catch (UnauthorizedAccessException e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        Console.WriteLine("FINISHED");

This will collect all files into the allFiles list (as paths) and directories into the allDirectories list. This runs for ~10 minutes for me, so don't debug to many times.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • This is more of a suggestion rather than an answer. Surely the OP wants to gather all the, denied or not, files. This is a good way to narrow them down though! – panoskarajohn Dec 26 '20 at 09:38
  • Thanks. But we do not have permission to access some files and folders.such as ((Document and Setting)).How can this problem be solved? – marandiiii Dec 26 '20 at 10:15
0

First thing you need to do is compiling your C# app with a manifest file that asks for root privileges (follow instructions from: How do I force my .NET application to run as administrator?). Next, What you should do is achieve any kind of a user/running-app with admin permissions and let it start your C# app. I think that if you'll do the above via an app with root privileges then no UAC will pop-up to the user when the C# app will start.

If your app don't have root permission you won't be able to read the directory tree of unauthorized folders. C# is a managed language, which means C# counts on the operating system to run and for that reason it can't bypass the operating system. Even with root permission, the operating system will be aware of your app actions.

BUT if your target is to figure out if a C# dll can maliciously read the folder tree of C drive, I think it's possible:

  1. You need to compile your C# code into a exe file with a manifest as I've described above.
  2. Then, create a batch file that will start a CLR process with root privileges (it'll probably alert the user with a UAC prompt but a common user won't suspect the CLR).
  3. Make sure your batch will run with the user privileges and not the default ones or the next step won't work.
  4. Your batch should tell the clr to load C# exe and I believe either no UAC will be prompted or either the batch could accept on behalves of the user without any prompt. 4'. If I'm wrong, perhaps the article https://www.codeproject.com/Articles/607352/Injecting-NET-Assemblies-Into-Unmanaged-Processes#PuttingItAllTogether will help you inject the exe into the clr without a UAC prompt.

Let me know if you continued the research by my suggestion and what was the results :-)

Adi Peled
  • 28
  • 5