5

Summary Of Problem:

I have a console app that, after copying many folders and files over to a new location, a local drive, it then deletes certain files/folders. One of these filetypes it deletes is .exe files. When trying to delete said files it gives me a denied access error.(This also occurs while trying to delete other kinds of files and folders as well)

Other Notes:

I saw several questions, such as Unable to delete .exe file through c#. However the process was never running on my local machine nor on the source it was copied from. I am both a local administrator and a domain administrator on our domain, and I had ownership over all folders and files in the directories I'm working with. But it still denies me access when trying to delete the file from code. I am however able to delete such files/folders manually.(click delete key)

Problem:

As stated above I am looking for a way to get past this issue denying me access to delete these "Illegal" file types and delete them from my code.

My Code:(Updated)

#region Delete_Illegal_Items
    public static void RemoveIllegalItems()
    {
        Console.Clear();
        DirectoryInfo Libraries = new DirectoryInfo(Library.DestinationMain);
        try
        {
            foreach (var Lib in Libraries.GetDirectories())
            {
                Console.WriteLine("Working On {0}.", Lib.Name);
                Parallel.Invoke(
                        () =>
                        {
                            RemoveBadFiles(Lib);
                        },

                        () =>
                        {
                            DeleteEmptyFolders(Lib);
                        }
                    );
            }
        }
        catch (AggregateException e)
        {
            Console.WriteLine("There Was An Unusual Error During Initialization Of Library Correction:\n{0}", e.InnerException.ToString());
        }
    }

    private static string[] BadFiles = { 
                                        @".hta",
                                        @".exe",
                                        @".lnk",
                                        @".tmp",
                                        @".config",
                                        @".ashx",
                                        @".hta.",
                                        @".hta::$DATA",
                                        @".zip",
                                        @".asmx",
                                        @".json",
                                        @".soap",
                                        @".svc",
                                        @".xamlx",
                                        @".msi",
                                        @".ops",
                                        @".pif",
                                        @".shtm",
                                        @".shtml",
                                        @"smt",
                                        @".vb",
                                        @".vbe",
                                        @".vbs",
                                        @".ds_store",
                                        @".db",
                                        @".ini",
                                        @".tiff"
                                      };
    private static void RemoveBadFiles(DirectoryInfo directory)
    {
        DirectoryInfo[] dirs = null;
        FileInfo[] files = null;
        if (directory != null)
        {
            files = directory.GetFiles();
        }

        try
        {
            dirs = directory.GetDirectories();
        }
        catch (IOException) { }
        catch (Exception e)
        {
            Console.WriteLine("\nError During Enumeration Of Items To Delete:\n{0}", e.Message);
        }

        if (files != null)
        {
            foreach (var file in files)
            {
                try
                {
                    if (file.IsReadOnly)
                    {
                        file.IsReadOnly = false;
                    }

                    if (BadFiles.Contains(Path.GetExtension(file.FullName)))
                    {
                        File.Delete(file.FullName);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError During Removal Or Illegal Files:\n" + e.Message);
                }
            }
        }

        if (dirs != null)
        {
            foreach (var dir in dirs)
            {
                switch (dir.Name)
                {
                    case ".TemporaryItems":
                        {
                            try
                            {
                                Directory.Delete(dir.FullName);
                            }
                            catch { }
                            break;
                        }
                    case "AI_RecycleBin":
                        {
                            try
                            {
                                Directory.Delete(dir.FullName);
                            }
                            catch { }
                            break;
                        }
                    case ".ToRemove":
                        {
                            try
                            {
                                Directory.Delete(dir.FullName);
                            }
                            catch { }
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
                RemoveBadFiles(dir);
            }
        }
    }

    private static void DeleteEmptyFolders(DirectoryInfo directory)
    {
        Program Main = new Program();
        try
        {
            DirectoryInfo[] dirs = directory.GetDirectories();

            foreach (var subDirectory in dirs)
            {
                int sum = Library.CountLibrary(subDirectory.FullName);

                if (sum == 0)
                {
                    Directory.Delete(subDirectory.FullName);
                }

                DeleteEmptyFolders(subDirectory);
            }
        }
        catch { }
    }
    #endregion

Any help would be greatly appreciated. If this question has been directly answered elsewhere please feel free to mention it in the comment. As I stated above I have been looking through past question regarding this issue and have not found a solution as of yet. Otherwise thank you for your help.

Community
  • 1
  • 1
CalebB
  • 597
  • 3
  • 17
  • What permissions does the User you console app runs under have on the system? Is the console app creating these files? – Greg Burghardt Dec 22 '14 at 18:11
  • It's running under me, the files are being copied from a network fileshare to a local drive where I have local admin rights. Also both the fileshare and local machine are inside a domain that I have full read/write access to everything under our domain. It's not creating anything, just copying and then deleting from the copied data. – CalebB Dec 22 '14 at 19:08
  • Which line causes the exception? Does this apply to any file or perhaps only to a particular file? – dymanoid Dec 22 '14 at 19:11
  • It's the File.Delete(file.FullName) in the first foreach under the RemoveBadFiles method. The exception itself is cought by the try/catch in the foreach but that's not really what I want in this case sense I still need the file deleted. Not that I've noticed. It started with a couple link files (.lnk) that I manually deleted but then stopped again on the .exe file which is where I started looking around for another answer and opened this question. – CalebB Dec 22 '14 at 19:17
  • While looking at the file's properties I noticed it was marked as read-only, this wouldn't cause any problems would it? – CalebB Dec 22 '14 at 19:22
  • I think that might have been it. I removed the read-only mark in the files properties and then it went through that file. Is there a way to get around this for the other .exes and such? – CalebB Dec 22 '14 at 19:24
  • I believe that was it. I updated my RemoveBadFiles method which seems to have fixed it. Testing it out now. – CalebB Dec 22 '14 at 19:36
  • Don't forget to add your fixed code as an answer. – Eris Dec 22 '14 at 20:38
  • @Eris I definitely will, thank you for the reminder. Just waiting for it to run through to make sure it works. It has to run through a little under half a million files/folders. – CalebB Dec 22 '14 at 20:40
  • In the future if you receive an exception that you don't understand, the first thing you should check is the online documentation. For example, the documentation for [File.Delete](http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx) lists four reasons why you might get an Unauthorized Access Exception. The last one says, "path specified a read-only file." – Jim Mischel Dec 22 '14 at 20:57

1 Answers1

1

Figured out the problem was with the files being marked as "Read-only" so I added a if statement before the deletion of the file to check if it was and remove the mark if need be. Here is the code that worked successfully for deleting all the wanted files.

#region Delete_Illegal_Items
    public static void RemoveIllegalItems()
    {
        Console.Clear();
        DirectoryInfo Libraries = new DirectoryInfo(Library.DestinationMain);
        try
        {
            foreach (var Lib in Libraries.GetDirectories())
            {
                Console.WriteLine("Working On {0}.", Lib.Name);
                Parallel.Invoke(
                        () =>
                        {
                            RemoveBadFiles(Lib);
                        },

                        () =>
                        {
                            DeleteEmptyFolders(Lib);
                        }
                    );
            }
        }
        catch (AggregateException e)
        {
            Console.WriteLine("There Was An Unusual Error During Initialization Of Library Correction:\n{0}", e.InnerException.ToString());
        }
    }

    private static string[] BadFiles = { 
                                        @".hta",
                                        @".exe",
                                        @".lnk",
                                        @".tmp",
                                        @".config",
                                        @".ashx",
                                        @".hta.",
                                        @".hta::$DATA",
                                        @".zip",
                                        @".asmx",
                                        @".json",
                                        @".soap",
                                        @".svc",
                                        @".xamlx",
                                        @".msi",
                                        @".ops",
                                        @".pif",
                                        @".shtm",
                                        @".shtml",
                                        @"smt",
                                        @".vb",
                                        @".vbe",
                                        @".vbs",
                                        @".ds_store",
                                        @"ds_store",
                                        @"._.Trashes",
                                        @".Trashes",
                                        @".db",
                                        @".dat",
                                        @".sxw",
                                        @".ini",
                                        @".tif",
                                        @".tiff"
                                      };
    private static void RemoveBadFiles(DirectoryInfo directory)
    {
        DirectoryInfo[] dirs = null;
        FileInfo[] files = null;
        if (directory != null)
        {
            try
            {
                files = directory.GetFiles();
            }
            catch (IOException) { }
        }

        try
        {
            dirs = directory.GetDirectories();
        }
        catch (IOException) { }
        catch (Exception e)
        {
            Console.WriteLine("\nError During Enumeration Of Items To Delete:\n{0}", e.Message);
        }

        if (files != null)
        {
            foreach (var file in files)
            {
                try
                {
                    if (file.IsReadOnly)
                    {
                        file.IsReadOnly = false;
                    }

                    if (BadFiles.Contains(Path.GetExtension(file.FullName)) || BadFiles.Contains(file.Name))
                    {
                        File.Delete(file.FullName);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError During Removal Or Illegal Files:\n" + e.Message);
                }
            }
        }

        if (dirs != null)
        {
            foreach (var dir in dirs)
            {
                switch (dir.Name)
                {
                    case ".TemporaryItems":
                        {
                            try
                            {
                                Directory.Delete(dir.FullName);
                            }
                            catch { }
                            break;
                        }
                    case "TemporaryItems":
                        {
                            try
                            {
                                Directory.Delete(dir.FullName);
                            }
                            catch { }
                            break;
                        }
                    case "AI_RecycleBin":
                        {
                            try
                            {
                                Directory.Delete(dir.FullName);
                            }
                            catch { }
                            break;
                        }
                    case ".ToRemove":
                        {
                            try
                            {
                                Directory.Delete(dir.FullName);
                            }
                            catch { }
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
                RemoveBadFiles(dir);
            }
        }
    }

    private static void DeleteEmptyFolders(DirectoryInfo directory)
    {
        Program Main = new Program();
        try
        {
            DirectoryInfo[] dirs = directory.GetDirectories();

            foreach (var subDirectory in dirs)
            {
                int sum = Library.CountLibrary(subDirectory.FullName);

                if (sum == 0)
                {
                    Directory.Delete(subDirectory.FullName);
                }

                DeleteEmptyFolders(subDirectory);
            }
        }
        catch { }
    }
    #endregion

Thank you to those that comment and helped. And hope this can help others in the future.

CalebB
  • 597
  • 3
  • 17
  • Consider making `BadFiles` a `HashSet`. `HashSet.Contains` will be much faster than `Array.Contains`. The `HashSet.Contains` does a direct lookup rather than a sequential search. It's not going to make any difference in runtime speed for this application because your limiting factor is disk I/O time, but it's a good general practice. – Jim Mischel Dec 22 '14 at 21:04