ITKeyword,专注技术干货聚合推荐

注册 | 登录

解决c# - Access Denied While Deleting .exe File

itPublisher 分享于

2020腾讯云双十一活动,全年最低!!!(领取3500元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1073

2020阿里云最低价产品入口,含代金券(新老用户有优惠),
地址https://www.aliyun.com/minisite/goods

推荐:Access to file"\\***\user.txt" denied

使用vss administrator添加新用户时报错,后来检查下,发下user.txt为只读属性,去掉就可以了 参考:http://liangliang.cnblogs.com/articles/80389.html

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)

推荐:解决VSS中Access to file "\\...\rights.dat" denied的错误

  出现此错误,是由于没有网络访问的权限导致。可能出现错误的原因: 1、  登录网上邻居时的用户名密码没有保存正确。 2、VSS客户端的用户名密码不正确。 解决方

#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.

c# .net access-denied
|
  this question
edited Dec 22 '14 at 19:35 asked Dec 22 '14 at 17:54 CalebB 496 3 15      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 file
  to a local drive where I have local admin rights. Also both the file
  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  |  show more comments

1 Answers
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.


|
  this answer
answered Dec 22 '14 at 20:47 CalebB 496 3 15      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. –  Jim Mischel Dec 22 '14 at 21:04      I will definitely look into that, thank you for the tips. –  CalebB Dec 22 '14 at 22:43

 | 

推荐:GAEUnit-ImportError: Access to module file denied

最近学习GAE,单元测试少不了的,写了一大段代码,结果测试一片红,错误提示信息:  GAEUnit错误堆栈信息 Traceback (most recent call last):   File  " D:\Pro


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。