Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.IO.File.WriteAllText throws exception for specific file name

Tags:

c#

.net

This has to be one of the strangest exceptions I have ever seen. When using the File.WriteAllText static method to write files, a particular file name cannot be written: "PRN". you can recreate this with a simple one liner:

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

I have tried different extensions, I have tried writing to different folders with this method, but in all cases, I get the following exception when trying to write a file with this specific file name:

FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of \"\\.\\" in the path.

the stack trace looks like the following:

   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

Any ideas why this would occur? I think I'm going to replace with my own file writer, but I found it crazy while a file name "PRD" would cause this system to blow up.

like image 505
Nathan Tregillus Avatar asked Dec 05 '14 00:12

Nathan Tregillus


1 Answers

This is not because of your code. PRN is an MSDOS device name and can't be used as a filename.

Use a different filename.

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

like image 64
gstar Avatar answered Sep 22 '22 18:09

gstar