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.