c# - 垃圾清理程序无法删除临时文件夹

标签 c# .net exception io

我无法删除临时文件夹目录。这是我的代码:

private void button8_Click(object sender, EventArgs e)
{
    if(checkBox5.Checked == true)
    {
        try
        {
            string fileDirectory = @"C:\Users\Admin\AppData\Local\Temp";
            if(Directory.Exists(fileDirectory))
            {
                Directory.Delete(fileDirectory);
            }
        }
        catch(IOException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    else
    {
        MessageBox.Show("System has been cleaned!");
    } 
}

最佳答案

您可以使用Path.GetTempPath()来获取当前用户的临时文件夹。 您不应该删除 Temp 目录本身。最好删除它的文件,跳过所有无法删除的文件:

System.IO.DirectoryInfo tempDir = new DirectoryInfo(Path.GetTempPath());

foreach (FileInfo file in tempDir.GetFiles())
{
    try
    {
        file.Delete(); 
    }
    catch(IOException ex)
    {
        .....
    }
}

另请参阅:"Directory is not empty" error when trying to programmatically delete a folder

关于c# - 垃圾清理程序无法删除临时文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987476/

相关文章:

c# - .NET 4.5 程序集可以引用 .NET 4.0 程序集吗?

exception - 如何在 .NET CORE 中使用 SqlException?

python - 从循环中重新抛出当前项目的异常

c# - 如何对异常错误进行分类?

c# - 在 C# 中,我如何根据值而不只是字母顺序对基于第二列的锯齿状二维矩形数组进行升序排序?

c# - 统一正则表达式

c# - 如何在 Azure 移动应用服务中获取 Cosmos Db 数据

c# - 如何创建打印文档的打印预览

c# - 使用 Rhino Mocks 模拟私有(private)对象调用

c# - 带有参数的 Dispatch.Invoke( new Action...)