如何修复路径中的“无效字符”错误,下载文件并按其标题命名时

本文关键字:文件 下载 标题 错误 路径 何修复 无效 无效字符 字符 | 更新日期: 2023-09-27 18:12:50

我得到一个无效的字符路径错误,我知道为什么我是,我的代码是基于一个视频的标题给文件名,视频有一个无效的字符是具体的,它是这个字符"|"从这个视频"GLORYHAMMER - Angus McFife"|"凝固汽油弹唱片"我只需要知道如何修理它。我正在使用YoutubeExtractor插件。

private void btnDownload_Click(object sender, EventArgs e)
{
    progressBar.Minimum = 0;
    progressBar.Maximum = 100;
    IEnumerable<VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(txtUrl.Text);
    VideoInfo video = videos.First(p => p.VideoType == VideoType.Mp4 && p.Resolution == Convert.ToInt32(cboResolution.Text));
    if (video.RequiresDecryption) 
    {
        DownloadUrlResolver.DecryptDownloadUrl(video);
    }
    VideoDownloader downloader = new VideoDownloader(video, Path.Combine(Application.StartupPath + "''", video.Title + video.VideoExtension));
    downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged;
    Thread thread = new Thread(() => { downloader.Execute(); }) { IsBackground = true };
    thread.Start();
}

我已经做了一些事情,比如做了一个if语句

if (video.Title.Contains("/"))
{
    video.Title.Replace("/", "");
}

或使用Regex,但我很快发现这是行不通的,因为我需要一个按键事件。我正在使用一个下载事件,它提取包含非法字符的标题。

如果你们能帮忙的话,我会很感激的!

如何修复路径中的“无效字符”错误,下载文件并按其标题命名时

下面是我用来创建"安全"文件名的代码片段:

internal static string GetSafeFileName(string fromString, char usingSafeReplacementChar)
{
    var invalidChars = System.IO.Path.GetInvalidFileNameChars();
    if (invalidChars.Contains(usingSafeReplacementChar))
        throw new System.ArgumentException(
        string.Format("'{0}' is not a valid safe replacement character.", 
        usingSafeReplacementChar));
    return new string(fromString.Select((inputChar) =>
        invalidChars.Any((invalidChar) =>
        (inputChar == invalidChar)) ? usingSafeReplacementChar : inputChar).ToArray());
}

你可以这样使用:

string newName = GetSafeFileName(video.Title, '_');