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 @ 2015-08-05 13:11  程序员徐坤  阅读(1235)  评论(0编辑  收藏  举报