使用 C# 根据 url 输入(特殊字符)创建 .url 文件

Create .url file based on url input (special characters) with C#

我正在创建一个基于 url 创建 .url 文件的程序。该文件应该以 URL 的 html 'title' 作为名称。文件内容为 url header。例如:

输入

https://www.youtube.com/watch?v=fRh_vgS2dFE

输出:文件名

Justin Bieber - Sorry (PURPOSE : The Movement).url

输出:文件内容

[InternetShortcut]
URL=https://www.youtube.com/watch?v=4Tr0otuiQuU

然而,当我插入示例中的歌曲时,问题就出现了。因为它有一个字符不受 Windows (:).

中文件名的支持

代码

string _Path = @"C:\Users\Public\Music\";
    private void bNewSong_Click(object sender, EventArgs e)
    {
        if (lbPlaylists.SelectedItem != null && lbPlaylists.SelectedItem.ToString() != "")
        {
            string songURL = Microsoft.VisualBasic.Interaction.InputBox("Enter song URL:", "New", lbPlaylists.SelectedItem.ToString(), 800, 450);
            if (songURL != "" && songURL.Contains(@"https://www.youtube.com/watch?v="))
            {
                WebClient x = new WebClient();
                string source = x.DownloadString(songURL);
                string title = Regex.Match(source, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
                title = title.Remove(title.Length - 10);
                string fullPath = _Path + lbPlaylists.SelectedItem.ToString() + "\" + title + ".url";

                if (!File.Exists(fullPath))
                {
                    using (StreamWriter writer = new StreamWriter(fullPath))
                    {
                        string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
                        writer.WriteLine("[InternetShortcut]");
                        writer.WriteLine("URL=" + songURL);
                        writer.Flush();
                    }
                }
                else
                {
                    MessageBox.Show("Song already in playlist.");
                }
            }
            else
            {
                MessageBox.Show("Enter a new playlist name.");
            }
        }
        else
        {
            MessageBox.Show("Select a playlist to add a song to.");
        }
    }

所以我的问题是:

如何将标题格式化为可接受的文件名?

提前致谢。

您可以替换

返回的无效字符
Path.GetInvalidFileNameChars()

https://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars(v=vs.110).aspx

例如:

foreach (var c in Path.GetInvalidFileNameChars())
    fullPath = fullPath.Replace(c, '-');