循环保存不同文件名文本文件报错:System.NotSupportedException(路径格式不支持)
解决System.NotSupportedException:路径格式不支持的问题
问题根源
- 路径转义错误:C#字符串里的反斜杠是转义字符,你写的
"C:\Users\Desktop\name{name}.txt"中,\U、\D会被当作无效转义序列,导致路径格式不被系统识别。 - 文件名含非法字符:
id.Text + date.Text拼接出的字符串可能包含Windows文件名禁止的字符(比如:、*、?、"、<、>、|),这些字符会触发路径格式异常。
修正代码
for (int i = 0; i < news.Count; i++) { var heading = title.Text; var body = articleBody.Text; var rawName = id.Text + date.Text; // 清理文件名中的非法字符,用下划线替换 char[] invalidChars = Path.GetInvalidFileNameChars(); var validName = string.Join("_", rawName.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)); // 使用逐字字符串避免转义问题(@前缀) var filePath = $@"C:\Users\Desktop\name{validName}.txt"; // 确保目标目录存在,不存在则创建 string dirPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } File.WriteAllText(filePath, heading + body); }
关键说明
- 用
Path.GetInvalidFileNameChars()获取所有系统禁止的文件名字符,通过拆分替换保证文件名合法。 - 路径前加
@前缀(逐字字符串),避免反斜杠被解析为转义字符;也可以用双反斜杠\\替代单个反斜杠。 - 增加目录存在性检查,避免因目录不存在抛出异常。
内容的提问来源于stack exchange,提问作者alireza najari
相关产品推荐
相关产品推荐

