C#判断并且去除掉路径和文件名中的非法字符
1/// <summary>
2 /// 去除掉文名中的非法字符
3 /// </summary>
4 /// <param name="fileName"></param>
5 /// <param name="repStr"></param>
6 /// <returns></returns>
7 public string invalidFileName(string fileName = "", string repStr = "_")
8 {
9 // 例如: fileName = "文件/名称"
10 foreach (char invalidChar in Path.GetInvalidFileNameChars())
11 {
12 fileName = fileName.Replace(invalidChar.ToString(), repStr);
13 }
14 //结果:文件_名称
15 return fileName;
16 }
17 /// <summary>
18 /// 去掉路径中的非法字符
19 /// </summary>
20 /// <param name="path"></param>
21 /// <param name="repStr"></param>
22 /// <returns></returns>
23 public string invalidPath(string path, string repStr = "_")
24 {
25 //剔除路径字符串中非法的字符
26 //例如 path = "路径\ds"
27 foreach (char invalidChar in Path.GetInvalidPathChars())
28 {
29 path = path.Replace(invalidChar.ToString(), repStr);
30 }
31
32 //结果:路径_ds
33 return path;
34 }