繁体   English   中英

打开C:直接使用`FileStream`而不使用`CreateFile` API

[英]Open C: Directly with `FileStream` without `CreateFile` API

我试图直接用FileStream打开C:但没有成功:

new FileStream("C:", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

System.UnauthorizedAccessException未处理

Message =“拒绝访问路径'C:\\'。”

来源= “mscorlib程序”

堆栈跟踪:

  in System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) in 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) in System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) in System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) in ReadingMftNewTest.Program.Main(String[] args) in D:\\CS\\2008\\ReadingMftNewTest\\ReadingMftNewTest\\Program.cs:line 76 

请注意,我打开“C:”,但错误显示“C:\\”,这个斜杠是从哪里来的? :\\

有没有机会打开C:不使用CreateFile API?

我真的不希望依赖于WIN32 API,因为此代码也应该在不支持WIN32 API的Mono上运行,但是使用常规FileStream(Mono 1 Microsoft 0)成功打开设备。

我终于找到了一种方法:

new FileStream(@"C:\$Volume", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

这仅适用于NTFS卷。

当您在名称中引用没有\\的根驱动器时,您使用的是文件系统中的别名。 它映射到该根驱动器下使用的最后一个工作目录。 这相当于在cmd窗口中输入d:c: . 它会将您移动到最后一个目录下的相应根驱动器。

在这种情况下, c:驱动器上使用的最后一个路径是c:\\ 所以当打开c:你最终打开c:\\

使用我所知道的FileStream API无法避免这种“别名”。 在调用CreateFile之前,所有FileStream API最终都将映射Path.NormalizePath给出的路径。 这是执行映射的函数。

打开驱动器需要驱动器名称,例如“\\\\。\\ PhysicalDrive0”。 查找驱动器名称需要QueryDosDevice()。 Windows允许这种情况的可能性相当小

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM