无法写入文件名为“aux”的任何路径

maf*_*afu 6 .net c# windows file

当尝试写入文件名“aux”的路径时,我很困惑地收到异常。同一目录和不同目录中的其他文件名都可以正常工作,我以前从未遇到过这种麻烦。

为了给您一个想法,请考虑以下测试代码:

Directory.CreateDirectory ("D:\\asdf"); // OK
File.WriteAllText ("D:\\asdf\\aux_", ""); // OK
try {
    File.WriteAllText ("D:\\asdf\\aux.txt", ""); // fails
}
catch (ArgumentException ex) {
    Console.WriteLine (ex);
}
try {
    File.WriteAllText ("D:\\asdf\\aux", ""); // fails
}
catch (ArgumentException ex) {
    Console.WriteLine (ex);
}
Console.WriteLine (string.Join ("\n", Directory.EnumerateFiles ("D:\\asdf")));
Run Code Online (Sandbox Code Playgroud)

最后一行打印创建了一个文件:

D:\asdf\aux_
Run Code Online (Sandbox Code Playgroud)

抛出两个相同的异常:

System.ArgumentException: FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\.\" in the path.
   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 Program.Main(String[] args) in C:\...\Program.cs:line 24
Run Code Online (Sandbox Code Playgroud)

替换\\为 并/没有改变任何东西(据我所知,这在 Windows 上是非标准的)。

我知道aux很久以前有一个特殊的含义,但考虑到它只出现在子目录中的文件名(带或不带扩展名)中,它不应该此相关。

Ste*_*eve 5

AUX 是文件的保留名称。它记录在 Microsoft Docs 的命名文件、路径和命名空间中,其中写道:

请勿使用以下保留名称作为文件名:CON、PRN、AUX、NUL、COM1、COM2、COM3、COM4、COM5、COM6、COM7、COM8、COM9、LPT1、LPT2、LPT3、LPT4、LPT5、 LPT6、LPT7、LPT8 和 LPT9。还要避免这些名称后紧跟着扩展名;例如,不建议使用 NUL.txt。