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.

10
  • What permissions does the User you console app runs under have on the system? Is the console app creating these files? Commented Dec 22, 2014 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. Commented Dec 22, 2014 at 19:08
  • Which line causes the exception? Does this apply to any file or perhaps only to a particular file? Commented Dec 22, 2014 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. Commented Dec 22, 2014 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? Commented Dec 22, 2014 at 19:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Consider making BadFiles a HashSet<string>. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.