删除指定文件夹下的所有指定类型的文件

本文介绍了一个用于检查文件类型的实用方法,并演示了如何递归地遍历目录来查找特定类型的文件,最后实现了对这些文件的删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public bool checkFileType(string type)
    {
        bool FileType = false;
        string[] type_ = new string[1];
        type = type.ToLower();
        type_[0] = ".bak";
        //type_[1] = ".gif";
        //type_[2] = ".jpeg";
        //type_[3] = ".png";
        //可在此添加上传文件的后缀名
        for (int i = 0; i < type_.Length; i++)
        {
            if (type.Contains(type_[i].ToString()))
            {
                FileType = true;
            }
        }
        return FileType;
    }
    public void GetFiles(string ObjDirPath)
    {
        string savePath = ObjDirPath;
        string absSavePath = Server.MapPath(savePath);
        DirectoryInfo SourceDir = new DirectoryInfo(absSavePath);
        foreach (FileSystemInfo FSI in SourceDir.GetFileSystemInfos())
        {
            if (FSI is DirectoryInfo)
            {
                //如果是文件夹则递归
                GetFiles(FSI.FullName);
            }
            else
            {
                //如果是符合要求的文件则垒加集合,因为我只要求显示图片文件,在checkFileType方法里定义要显示文件的扩展名
                if (checkFileType(FSI.Extension))
                {
                    //由于是物理路径,如e:/luobing_web/uploadfiles/picture/test.jpg这种形式,需要提取虚拟路径,如:../uploadfiles/picture/test.jpg
                    string FilePath = FSI.FullName.ToLower();//一步写来看起混乱,就分开写了
                    //FilePath = FilePath.Substring(FilePath.LastIndexOf("tiaoxingma//"));
                    FilePath = FilePath.Replace("//", @"/");//这里在路径前加了../,因为我的项目里页面文件和上传文件夹不是同级文件夹
                    //File_List += FilePath + ",";
                    FilePicDelete(FilePath);
                }
            }
        }
    }
    public static bool FilePicDelete(string path)
    {
        bool ret = false;
        System.IO.FileInfo file = new System.IO.FileInfo(path);
        if (file.Exists)
        {
            file.Delete();
            ret = true;
        }
        return ret;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值