Writing a File that has the Name of a Device

一曲冷凌霜 提交于 2019-12-01 03:25:57

The reserved names are AUX, CLOCK$, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, CON, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9, NUL and PRN.

You won't be able to create files with these names (and with any extension, e.g. COM2.txt on Windows on any File System - that's a Windows Kernel enforced thing, for backwards compatibility with CP/M. It MAY be a limitation on FAT filesystems though, but it's not on NTFS. See Wikipedia for some more info.

However, you can try to use UNC File Names, these should to work:

echo test > com2.txt
-> The system cannot find the file specified.

echo test > \\mypc\c$\Users\Michael\Desktop\com2.txt
-> works flawlessly

I'm not 100% sure if UNC Paths work with File Stream, but there certainly is a way to use them in .net.

Wrap the call to "new FileStream" with a try/catch block to specifically catch System.ArgumentException. If you catch this, assume the the filename is invalid and try again with a different filename (e.g. prepend "foo" to the filename string).

Also, you can use System.IO.Path.GetInvalidPathChars() and System.IO.Path.GetInvalidFileNameChars(); to get the complete list of "invalid characters" that won't fit inside a windows filename. So you can strip out or replace those chars fromthe filename string before attempting to create the file.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!