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

时间:2016-01-26 13:53:35

标签: c# file url character title

我正在创建一个基于url创建.url文件的程序。该文件应该包含网址  html'标题'作为名字。文件的内容是url标头。例如:

输入

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.");
        }
    }

所以我的问题是:

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

提前致谢。

1 个答案:

答案 0 :(得分:3)

您可以替换

返回的无效字符
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, '-');