2

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

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

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

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

4

2 回答 2

7

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

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

这个类似的线程显示了如何为卫生目的进行字符串替换的方法: C# Sanitize File Name

如果该链接出现故障,以下是该线程的一个很好的答案:

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, "_" );
}
于 2012-08-27T01:29:34.283 回答
0

如果它由于 StreamWriter 构造函数上的异常而崩溃(看起来很可能),您可以简单地将其放在异常捕获块中。

这样,您可以让您的代码处理这种情况,而不仅仅是陷入困境。

换句话说,类似:

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 
}

在变形文件名以使其可接受方面,这里回答了大量文件系统中允许的字符列表。

基本上,此 Wikipedia 页面( Comparison of filename limitations) 中的第二个表显示了允许和不允许的内容。

您可以使用正则表达式替换来确保将所有无效字符转换为有效字符,例如_,或完全删除。

于 2012-08-27T01:48:08.993 回答