【发布时间】:2016-01-26 13:53:35
【问题描述】:
我正在创建一个基于 url 创建 .url 文件的程序。该文件应该以 URL 的 html 'title' 作为名称。文件的内容是 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.");
}
}
所以我的问题是:
如何将标题格式化为可接受的文件名?
提前致谢。
【问题讨论】:
标签: c# file url character title