2

I'm programmatically writing to a file like this:

file = new StreamWriter("C:\\Users\\me\\Desktop\\test\\sub\\" + post.title + ".txt");
file.Write(postString);
file.Close();

However, sometimes the program crashes because illegal characters for a file name are in post.title. Characters like < and ".

How can I transform post.title into a safe filename?

tshepang
  • 12,111
  • 21
  • 91
  • 136
James Dawson
  • 5,309
  • 20
  • 72
  • 126
  • 2
    Unless you're doing some internal development for within your company, you should rather user `Environment.SpecialFolder.Desktop` instead of the hard-coded path. – Guillaume Aug 27 '12 at 01:39

2 Answers2

7

The general approach is to scrub the post.title value for characters in Path.GetInvalidFileNameChars()

http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx

This similar thread shows approaches on how to do string replacements for sanitation purposes: C# Sanitize File Name

In case that link goes down, here's a pretty good answer from the thread:

private static string MakeValidFileName( string name )
{
   string invalidChars = Regex.Escape( new string( Path.GetInvalidFileNameChars() ) );
   string invalidReStr = string.Format( @"[{0}]+", invalidChars );
   return Regex.Replace( name, invalidReStr, "_" );
}
Community
  • 1
  • 1
jglouie
  • 12,523
  • 6
  • 48
  • 65
  • A good answer, just keep in mind the caveat: "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." - you may need to tailor per filesystem type. – paxdiablo Aug 27 '12 at 01:49
0

If it's crashing due to an exception on the StreamWriter constructor (as seems likely), you can simply place that within an exception catching block.

That way, you can make your code handle the situation rather than just falling in a heap.

In other words, something like:

try {
    file = new StreamWriter ("C:\\Users\\me\\sub\\" + post.title + ".txt");
catch (Exception e) {  // Should also probably be a more fine-grained exception
    // Do something intelligent, notify user, loop back again 
}

In terms of morphing a filename to make it acceptable, the list of allowable characters in a large number of file systems was answered here.

Basically, the second table in this Wikipedia page (Comparison of filename limitations) shows what is and isn't allowed.

You could use regex replacement to ensure that all the invalid characters are turned into something valid, such as _, or removed altogether.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953