2016-01-26 109 views
0

我正在創建一個基於URL創建.url文件的程序。該文件應該具有URL的html'標題'作爲名稱。該文件的內容是url標頭。例如:基於URL輸入(特殊字符)創建.url文件與C#

輸入

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

所以我的問題是:

我如何格式化標題是一個可以接受的文件名?

在此先感謝。

回答