知识学堂 > 课程 > asp.net 查询指定文件夹下的文件删除

asp.net 查询指定文件夹下的文件删除

发布日期:2023/9/18 来源:聚恒【返回】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;


public partial class _2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        ///查询指定文件夹下所有文件
        string path = Server.MapPath("Management/Common/BianJiKuang/attached/file");
        DirectoryInfo di = new DirectoryInfo(path);


        //找到该目录下的文件夹
        foreach (DirectoryInfo sub in di.GetDirectories())
        {


            //找到该目录下的文件 
            DirectoryInfo di_1 = new DirectoryInfo(path + "/" + sub.Name);


            FileInfo[] fis = di_1.GetFiles();
            foreach (FileInfo fi in fis)
            {
                //    Response.Write(fi.Name);//文件名称  不包含文件夹
                //    Response.Write(fi.Length);//文件大小
                //    Response.Write(fi.FullName);//文件名称路径




                if (fi.Name.IndexOf(".html") >= 0)
                {
                    DeleteFile(fi.FullName);
                }
            }


        }




    }
    public static void CreateFolder(string FolderPathName)
    {
        if (FolderPathName.Trim().Length > 0)
        {
            try
            {
                string CreatePath = System.Web.HttpContext.Current.Server.MapPath("Management/Upload/" + FolderPathName).ToString();
                if (!Directory.Exists(CreatePath))
                {
                    Directory.CreateDirectory(CreatePath);
                }
            }
            catch
            {
                throw;
            }
        }
    }
    public void DeleteFile(string SourceFile)
    {
        if (System.IO.File.Exists(SourceFile))
        {
            System.IO.File.Delete(SourceFile);
        }
    }
}