Reputation: 447
I am creating a program that creates .url files based on a url. The file is supposed to have the URL's html 'title' as name. With the content of the file being the url header. For example:
Input
https://www.youtube.com/watch?v=fRh_vgS2dFE
Output: File name
Justin Bieber - Sorry (PURPOSE : The Movement).url
Output: File content
[InternetShortcut]
URL=https://www.youtube.com/watch?v=4Tr0otuiQuU
however the problem arises when I insert songs like the one in the example. Since it has a character unsupported by filenames in Windows (:).
Code
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.");
}
}
So my question is:
How do I format the title to be a acceptable file name?
Thanks in advance.
Upvotes: 0
Views: 826
Reputation: 4833
You can replace invalid characters returned by
Path.GetInvalidFileNameChars()
https://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars(v=vs.110).aspx
For example:
foreach (var c in Path.GetInvalidFileNameChars())
fullPath = fullPath.Replace(c, '-');
Upvotes: 3