C# 批量更改文件后缀名称

 解决问题思路

解决固定文件夹下更改文件后缀名,采用轮询的方式,

流程如下:

  1. 获取当前文件名(带后缀的文件名)
  2. 截取文件名称,去掉后缀
  3. 另存为带更改后的后缀文件

注意:采用第三方插件,附:源码和插件

开发工具:vs2022

库环境:.net Framework4.8

引用插件库:LongHunFramework

二、程序介绍

1.获取需要修改文件所在文件夹,及需要修改文件的后缀名


string dirPath = "G:\\Code\\demo2\\GRJ2A\\bin\\data\\map\\tiles";//Console.ReadLine();

if (Directory.Exists(dirPath))

{

    string hbStr_DictionaryPath = dirPath;

    List<string> hbListStr_AllFile = new List<string>();

    string dirPath = "G:\\Code\\demo2\\GRJ2A\\bin\\data\\map\\tiles";//Console.ReadLine();

    if (Directory.Exists(dirPath))

    {

       string hbStr_DictionaryPath = dirPath;

       List<string> hbListStr_AllFile = new List<string>();
        //! 获取全部png

       hlFileIO.hfjGetAllFileListByExtension(hbStr_DictionaryPath,             ref hbListStr_AllFile, ".png");

    }

    //! 获取全部png

    hlFileIO.hfjGetAllFileListByExtension(hbStr_DictionaryPath, ref hbListStr_AllFile, ".png");

}

dirPath路径为需要修改文件所在文件夹路径,操作前需要判断当前文件夹是否存在,如果存在可以执行下一步,如过不存在,则退出。

Ref:为net程序返回变量,hbListStr_AllFile变量前加上ref后,hbListStr_AllFile会输出该方法的返回值;

  1. 遍历修改文件后缀名,并保存
//! 遍历文件解决

                for (int i = 0; i < hbListStr_AllFile.Count; i++)

                {
                    string nowOldFileFullName = hbListStr_AllFile[i];//获取当前文件全路径,  例如 c:/83838/3/3/3/43/4/122.png
                    string hbOldFileName = Path.GetFileName(nowOldFileFullName);//返回 122.png 这样的文件名
                    string hbDictionary = Path.GetDirectoryName(nowOldFileFullName);// 返回 目录,例如 "c:/83838/3/3/3/43/4"
                    string hbOldFileOnlyName  = Path.GetFileNameWithoutExtension(nowOldFileFullName);// 获取"122"这样的名称
                    string hbNewFileName = hbOldFileOnlyName + ".jpg"; //新的名字 "122.jpg"
                    string newFileFullPath = Path.Combine(hbDictionary, hbNewFileName); //新文件的全路径, 例如 " c:/83838/3/3/3/43/4/122.jpg"
                    if (File.Exists(newFileFullPath))

                    {
                        Console.WriteLine($"因为已经存在[{newFileFullPath}], 所以没有对文件[{nowOldFileFullName}]进行操作!");
                    }
                    else
                    {
                        hlFileIO.hfjMoveAFile(nowOldFileFullName, newFileFullPath, true);
                    }
                    Console.WriteLine($"{i}/{hbListStr_AllFile.Count} 已修改完成...");
                }

提示:如果想修改多层级的文件夹,需要用到递归算法,递归每一层级的文件夹下的文件

亲测可用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值