确保文件名在创建之前有效

Jam*_*son 2 c# file-io file

我是以编程方式写入这样的文件:

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

但是,有时程序崩溃,因为文件名的非法字符在post.title.字符喜欢<".

如何转换post.title为安全文件名?

jgl*_*uie 7

一般的方法是擦除post.title字符的值Path.GetInvalidFileNameChars()

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

这个类似的线程显示了如何为卫生目的进行字符串替换的方法: C#清理文件名

如果链接断开,这是一个非常好的答案:

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, "_" );
}
Run Code Online (Sandbox Code Playgroud)