重庆熊猫 Loading

C#实现[移除文件名中的非中文字符]

更新记录:
2022年5月28日 从程序中抽出方法复用。

处理财务文件时写的一个小函数。用于移除文件名中的非中文字符。

/// <summary>
/// 移除文件名中的非中文字符
/// 比如:FJ_其他应付款!20210126_145109.xls 中的 FJ_、!20210126_145109
/// 将返回:其他应付款.xls
/// </summary>
/// <param name="filename">最原始的文件名</param>
/// <returns>处理好的文件名</returns>
static string RemoveFileNameIfNotChineseChar(string filename)
{
    //需要移除的字符
    char[] notNeedChars = new char[] { ' ', '_', '-', '@', '&', '*', '`', '!', '!', '~', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };

    //最终返回的文件名
    StringBuilder resultFileNameWithoutExtension = new StringBuilder();

    //遍历文件名去不必要的字符
    foreach (char item in Path.GetFileNameWithoutExtension(filename))
    {
        //如果不是不必要的字符
        if (!notNeedChars.Contains(item))
        {
            resultFileNameWithoutExtension.Append(item);
        }
    }

    //返回时加上扩展名
    return resultFileNameWithoutExtension.ToString() + Path.GetExtension(filename);
}
posted @ 2022-05-28 23:08  重庆熊猫  阅读(130)  评论(0编辑  收藏  举报