- BOM 是在 UTF-8 编码中用于标识文件字节顺序的特殊字符序列。尽管在 UTF-8 中它不是必需的,但在某些环境下会被添加到文件的开头。
- 移除 BOM 可以确保你的 UTF-8 文本文件在不同操作系统和编辑器中都能够正确解析和处理,避免因为 BOM 导致的解析错误或乱码问题。
1,递归读取文件中所有.lua.txt文件,并添加到txtFiles中
public static void GetLuaFiles(string folderPath,List<string> txtFiles)
{
txtFiles.AddRange(Directory.GetFiles(folderPath, "*.lua.txt"));
// 获取子文件夹中的所有*.lua.txt文件
foreach (string subDirectory in Directory.GetDirectories(folderPath))
{
GetLuaFiles(subDirectory, txtFiles);
}
}
2.去除所有.lua.txt文件的BOM头
public static void DelLuaBOM()
{
List<string> txtFiles = new List<string>();
foreach (string luaFolder in luaFolders)
{
string path = Path.Combine(Application.dataPath, luaFolder.Substring(7));
GetLuaFiles(path, txtFiles);
}
foreach (string filePath in txtFiles)
{
byte[] bom = { 0xEF, 0xBB, 0xBF };
byte[] fileBytes = File.ReadAllBytes(filePath);
if (fileBytes.Length >= 3 && fileBytes[0] == bom[0] && fileBytes[1] == bom[1] && fileBytes[2] == bom[2])
{
byte[] newBytes = new byte[fileBytes.Length - 3];
Array.Copy(fileBytes, 3, newBytes, 0, newBytes.Length);
File.WriteAllBytes(filePath, newBytes);
}
}
}