You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环保存不同文件名文本文件报错:System.NotSupportedException(路径格式不支持)

解决System.NotSupportedException:路径格式不支持的问题

问题根源

  1. 路径转义错误:C#字符串里的反斜杠是转义字符,你写的"C:\Users\Desktop\name{name}.txt"中,\U、\D会被当作无效转义序列,导致路径格式不被系统识别。
  2. 文件名含非法字符: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 03:22:49