批处理文件重命名
前言:对与多个文件重命名操作,文件数量少还好,但如果文件数量超过一定数量之后,一个个手动去重命名的话,实在是繁琐了,所以写个批处理文件重命名,简单快捷又方便٩(๑❛ᴗ❛๑)۶。
这里我写了个工具类,放在Unity 编辑器的菜单同居栏上,方便操作运行。
如图,点击重命名文件即可自行执行.
我这里是 预先 保存重命名后的文件名到列表或数组中(如果觉得脚本里面不好修改,可保存在外部文本,编译时再进行文件的读取操作)。
示例:
先建立几个需要重命名的文件
然后在Unity 编辑器中,找到Tools 工具,点击后重命名操作。
完整代码:
using System;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEditor;
public class RenameUtil : EditorWindow
{
private string filePath;
private List<string> fileOldList;
private List<string> fileNewList;
private string[] m_newList = { "001", "002", "003", "004" };
private string[] m_oldList = { "aa", "bb", "cc", "dd" };
// 添加 到Tool 菜单栏 : EditorWindow
[MenuItem("Tools/文件重命名")]
static public void OpenBMFontMaker()
{
EditorWindow.GetWindow<RenameUtil>(false, "Rename", true).Show();
}
private void OnGUI()
{
if (GUILayout.Button("重命名文件"))
{
Init();
RenameFile();
}
}
void Init()
{
int index = 0;
// 添加 重名后的文件名 到列表中
DirectoryInfo directory = new DirectoryInfo(filePath); // 遍历文件目录
fileNewList = new List<string>();
for (int i = 0; i < directory.GetFiles().Length; i++)
{
FileInfo file = directory.GetFiles()[i];
string str = file.Name.Substring(file.Name.Length - 4);
if (str == ".txt")
{
//fileNewList.Add(string.Format("{0}/{1}.txt", filePath, m_newList[index])); // 可下面语句 交叉测试使用
fileNewList.Add(string.Format("{0}/{1}.txt", filePath, m_oldList[index]));
Debug.Log("\n ====== 22222 当前文件名:" + fileNewList[index]);
index++;
}
}
// 缺点:无法确保命名前与命名后是否是同一个文件, 只能通过文件顺序 index 与要修改的文件名一一对应
}
private void RenameFile()
{
// 遍历 获取需要修改的 文件名
filePath = string.Format("{0}/Resources/rename", Application.dataPath);
DirectoryInfo directory = new DirectoryInfo(filePath); // Application.dataPath : 项目的Asset 目录
FileInfo[] fileList = directory.GetFiles();
int j = 0;
for (int i = 0; i < fileList.Length; i++)
{
string str = fileList[i].Name.Substring(fileList[i].Name.Length - 4); // 截取 文件后缀为 ".txt"
if (str == ".txt")
{
FileInfo file = fileList[i];
fileOldList.Add(file.Name);
//file.MoveTo(string.Format("{0}/{1}.txt", filePath, m_oldList[j]));
Debug.Log("\n ====== 33333 当前文件名:" + fileNewList[j]);
file.MoveTo(fileNewList[j]);
j++;
}
}
}
}
后记:
如有兴趣的,可尝试一下 File.Move("原路径文件名","新路径文件名"); 方法实现。