asp.net如何实现删除文件夹及文件内容操作

使用简单的几行代码即可实现文件删除功能,仅供参考学习

写法一:   

static void DeleteDirectory(string dir)
    {
        if (Directory.GetDirectories(dir).Length == 0 && Directory.GetFiles(dir).Length == 0)
        {
            Directory.Delete(dir);//删除文件夹,若不删除文件夹则不需要 Directory.Delete(dir)
            return;
        }
        foreach (string var in Directory.GetDirectories(dir))
        {
            DeleteDirectory(var);
        }
        foreach (string var in Directory.GetFiles(dir))
        {
            File.Delete(var);
        }
        Directory.Delete(dir));//删除文件夹,若不删除文件夹则不需要 Directory.Delete(dir)
    }

 调用方法如:

    protected void Button_Click(object sender, EventArgs e)
    {

        string dir = "E:/HQSearch/upfiles/";
        DeleteDirectory(dir);
        Response.Write("<script>alert('清除成功!');location='Default.aspx'</script>");

    }

 或者更为简洁的写法

    protected void Button_Click(object sender, EventArgs e)
    {
        foreach (string d in Directory.GetFileSystemEntries("E:/HQSearch/upfiles/20090118030907.xls"))
            {
                if (File.Exists(d))
                {
                    File.Delete(d); //直接删除其中的文件   
                    Response.Write("<script>alert('清除成功!');location='Default.aspx'</script>");
                }
            }
        }

posted @ 2009-10-26 15:06  独行剑  阅读(3823)  评论(0编辑  收藏  举报