Skip to content

Validating filenames

February 27, 2008

So I’m working on a project that grabs a Shoutcast stream and saves the songs out as MP3s with tags and all.  Obviously the artist – title.mp3 filename won’t always be valid off the bat.  I was a bit shocked that the following line wasn’t good enough.

cleanTitle = Regex.Replace(title, @”[^A-Za-z0-9 -]]”, “”, RegexOptions.CultureInvariant);

The classical guitar channel busted right through it.  The Spanish upsidedown question mark thingie seems to translate late into a regular question mark and still make it into the filename.

After some searching System.IO came to the rescue.  I had no idea there was a Path class.

foreach (char c in Path.GetInvalidFileNameChars())

{

cleanTitle = cleanTitle.Replace(c, ‘ ‘);

}

 

Anyone got a better approach?

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: