文件名/路径去除非法字符的方法,CSV格式文件Encode方法

1. 文件名去除非法字符

/// <summary>
/// Remove invalid characters which are not allowed in the file name
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string RemoveFileNameInvalidChar(this string fileName)
{
    if (string.IsNullOrEmpty(fileName))
        return fileName;
    string invalidChars = new string(Path.GetInvalidFileNameChars());
    string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars));
    return Regex.Replace(fileName, invalidReStr, "");
}

 

2. 文件路径去除非法字符

/// <summary>
/// Remove invalid characters which are not allowed in the path names
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string RemovePathInvalidChar(this string filePath)
{
    if (string.IsNullOrEmpty(filePath))
        return filePath;
    string invalidChars = new string(Path.GetInvalidPathChars());
    string invalidReStr = string.Format("[{0}]", Regex.Escape(invalidChars));
    return Regex.Replace(filePath, invalidReStr, "");
}

 

3. 输出CSV格式的文件时的Encode方法

/// <summary>
/// Encode the field in the CSV format file
/// </summary>
/// <param name="field">CSV field string</param>
/// <returns>Encoded field string</returns>
public static string CsvFieldEncode(this string field)
{
    if (string.IsNullOrEmpty(field))
        return field;
    bool quotesRequired = field.Contains(",");
    bool escapeQuotes = field.Contains("\"");
    string fieldValue = (escapeQuotes ? field.Replace("\"", "\"\"") : field);
    return string.Format("{0}{1}{0}",
            (quotesRequired || escapeQuotes ? "\"" : string.Empty),
            fieldValue);
}

 

原创文章,转载请注明: 转载自闲云博客

本文链接地址: 文件名/路径去除非法字符的方法,CSV格式文件Encode方法

发表评论

电子邮件地址不会被公开。 必填项已用*标注