1

我在 C# 中编写了一个简单的(控制台)脚本,它递归地删除给定参数 ex 中的文件和文件夹:delete_folder.exe "C:\test"

我在卸载期间使用这段小代码来删除卸载后的剩余文件。代码本身工作正常,但我收到错误:System.IO.IOException: The process cannot access the file 'C:\test\test2' because it is being used by another process.

就在此错误之前,卸载程序停止并删除了几个服务(由安装程序创建)

在我看来,Windows 仍然使用该文件夹test2。所以我的问题是:如何检查一个文件夹是否被另一个进程使用以及如何阻止该进程在那里,以便能够删除剩余的文件夹。

控制台应用程序如下所示:

class Program
    {
        public static void log(string t)
        {
            File.AppendAllText("C:\\testlog.txt", DateTime.Now.ToString() + "----" + t + "\r\n");
        }
        static void Main(string[] args)
        {
            try
            {
                string path = args[0];
                if (Directory.Exists(path) == true)
                {
                    Directory.Delete(path, true);
                }
                else
                {
                    Console.WriteLine("Dir not found!");
                }
            }
            catch (Exception ex)
            {
                log(ex.ToString());
            }
        }
    }
4

1 回答 1

1

Atry...catch可能听起来不太优雅(实际上,在大多数情况下,基于此语句的算法的正常流程是不可取的),但似乎是唯一的方法。请记住,没有System.IO(直接)属性可以告诉您是否正在使用元素;因此依靠这是解决此类问题的通常解决方案(有关文件正在使用的帖子)。示例代码:

foreach (string dir in System.IO.Directory.GetDirectories(rootDirectory))
{
    try
    {
        System.IO.Directory.Delete(dir);
    }
    catch
    {
        //There was a problem. Exit the loop?
    }
}
于 2013-10-04T08:10:45.663 回答