System.IO.File.WriteAllText 会引发特定文件名的异常

本文关键字:文件名 异常 IO File WriteAllText System | 更新日期: 2023-09-27 18:33:14

这一定是我见过的最奇怪的例外之一。使用 File.WriteAllText 静态方法写入文件时,不能写入特定的文件名:"PRN"。您可以使用简单的一行重新创建它:

File.WriteAllText("c:''Temp''PRN.txt", "write this to a file");

我尝试了不同的扩展名,我尝试使用此方法写入不同的文件夹,但是在所有情况下,尝试使用此特定文件名写入文件时都会出现以下异常:

FileStream 不会打开 Win32 设备,例如磁盘分区和 磁带驱动器。避免在路径中使用 ''"''''.''''"。

堆栈跟踪如下所示:

   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   at System.IO.File.InternalWriteAllText(String path, String contents, Encoding encoding, Boolean checkHost)
   at System.IO.File.WriteAllText(String path, String contents)
   at WriteAllTextThrowsExceptionWithPRN.UnitTest1.TestMethod1() in c:'Users'ntregillus'Documents'Visual Studio 2013'Projects'WriteAllTextThrowsExceptionWithPRN'WriteAllTextThrowsExceptionWithPRN'UnitTest1.cs:line 14

知道为什么会发生这种情况吗?我想我要用我自己的文件编写器替换,但我发现它很疯狂,而文件名"PRD"会导致这个系统爆炸。

System.IO.File.WriteAllText 会引发特定文件名的异常

这不是因为你的代码。PRN 是 MSDOS 设备名称,不能用作文件名。

使用其他文件名。

https://support.microsoft.com/en-us/kb/74496