Reputation: 5409
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?
Upvotes: 2
Views: 942
Reputation: 881123
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.
Upvotes: 0
Reputation: 12880
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, "_" );
}
Upvotes: 7