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

如何解决文件下载保存时的「路径中存在非法字符」问题?

解决C#异步下载时文件名含非法字符的问题

问题根源

Windows文件系统禁止文件名包含以下字符:<, >, :, ", /, \, |, ?, *。你遇到的报错是因为文件名里的?属于非法字符,而()是合法字符,所以问题出在?上。

解决方案

我们可以通过自动替换文件名中的非法字符为合法字符(比如下划线_)来解决,既不跳过文件,又能保留原文件名的可读性。

步骤1:编写文件名清理方法

创建一个静态方法,专门处理非法字符替换:

public static string GetSafeFileName(string filePath)
{
    // 获取系统禁止的文件名非法字符列表
    char[] invalidChars = Path.GetInvalidFileNameChars();
    // 拆分文件名和扩展名,单独处理文件名部分
    string directory = Path.GetDirectoryName(filePath);
    string fileName = Path.GetFileNameWithoutExtension(filePath);
    string extension = Path.GetExtension(filePath);
    
    // 将非法字符替换为下划线
    string safeFileName = string.Join("_", fileName.Split(invalidChars));
    
    // 拼接回完整路径
    return Path.Combine(directory, safeFileName + extension);
}

这个方法会精准处理文件名里的非法字符,同时保留原始文件扩展名,避免误处理。

步骤2:修改下载方法,提前清理路径

在原DownloadFile方法中,先对传入的location进行清理,再用处理后的路径执行下载:

public async Task DownloadFile(string urlAddress, string location)
{
    Stopwatch sw = new Stopwatch();
    // 清理路径,替换非法字符
    string safeLocation = GetSafeFileName(location);

    using (WebClient webClient = new WebClient())
    {  
        webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(((sender, e) => Completed(sender, e, sw)));
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, sw));

        Uri URL = new Uri(urlAddress);

        sw.Start();

        try
        {
            // 使用清理后的合法路径下载
            await webClient.DownloadFileTaskAsync(URL, safeLocation);
        }
        catch (Exception ex)
        {
            this.Invoke(new Action(() =>
                    {
                        Uri t = URL;
                        string tt = safeLocation;
                        MessageBox.Show(ex.ToString());
                    }));
        }
    }
}

效果验证

以你提供的示例文件名Ghost While They Sleep (FUNNY?).mp4为例,经过处理后会变成Ghost While They Sleep (FUNNY_).mp4,既保留了原文件名的核心信息,又符合Windows命名规则,不会再触发非法字符报错。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:05:23