110,502
社区成员
发帖
与我相关
我的任务
分享
string path = f;
string newpath = path;
string fullname = Path.GetFileName(path);//返回文件名和后缀名
string name = Path.GetFileNameWithoutExtension(path);//返回文件名
string extn = Path.GetExtension(path);//返回后缀名
byte[] Bytes = System.Text.Encoding.Default.GetBytes(fullname);//获得文件名+后缀名的字节数组
byte[] nameBytes = System.Text.Encoding.Default.GetBytes(name);//获得文件名的字节数组
byte[] extnBytes = System.Text.Encoding.Default.GetBytes(extn);//获得后缀名的字节数组
string newname = fullname;//新(文件名+后缀名)
while (Bytes.Length > 128)
{
int cutCount = Bytes.Length - 128;
int initialCopyCount = nameBytes.Length - cutCount;
int finalCopyCount;
int notAsciiBytesNumber = 0;
for (int i = initialCopyCount; i < nameBytes.Length; i++)
{
if (nameBytes[i] > 127)
notAsciiBytesNumber++;
else
break;
}
//排除误截汉字编码的可能
if (nameBytes[initialCopyCount - 1] > 127)
{
if (nameBytes[initialCopyCount - 2] > 127)
{
if (notAsciiBytesNumber % 2 == 0)
{
finalCopyCount = initialCopyCount;
}
else
{
finalCopyCount = initialCopyCount - 1;
cutCount = cutCount + 1;
}
}
else
{
finalCopyCount = initialCopyCount - 1;
cutCount = cutCount + 1;
}
}
else
finalCopyCount = initialCopyCount;
ArrayList al = new ArrayList();
al.InsertRange(0, nameBytes);//这里是将文件名部分完全添加到ArrayList中
al.RemoveRange(finalCopyCount, cutCount);//根据需要截取的长度,删除ArrayList中多余的元素
al.InsertRange(finalCopyCount, extnBytes);//将后缀名部分添加到ArrayList的最后
byte[] newNameBytes = new byte[al.Count];//根据ArrayList中的元素数目新建字节数组
al.CopyTo(newNameBytes);//将ArrayList中的所有元素复制到新文件名的字节数组中
newname = System.Text.Encoding.Default.GetString(newNameBytes);//将新文件名的字节数组编码成字符串
newpath = Path.GetDirectoryName(path).TrimEnd('\\') + "\\" + newname;
break;
}
File.Move(path, newpath);//改文件名
//传入校验前字符数组,及返回数组的最大长度,返回校验后不包含不完整字符的字符数组
Byte[] GetCheckedArr(Byte[] btArr, int iMaxLen)
{
if (iMaxLen >= btArr.Length || iMaxLen <= 0 || btArr == null)
{
return btArr;
}
//定义一个bool类型,指示字符是否完整
Boolean isComplete = true;
for (int i = 0; i < iMaxLen; i++)
{
//判断是否为汉字
if (btArr[i] > 127)
{
isComplete = !isComplete;
}
}
if (!isComplete)
{
--iMaxLen;
}
if (iMaxLen == 0)
{
return null;
}
Byte[] btReturn = new Byte[iMaxLen];
Array.Copy(btArr, 0, btReturn, 0, iMaxLen);
return btReturn;
}