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

时间:2010-02-13 17:32:11

标签: c# .net mono filestream device

我试图直接使用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:\”,这个斜杠是从哪里来的? :\

是否有机会在不使用CreateFile API的情况下打开C:

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

3 个答案:

答案 0 :(得分:2)

我终于找到了一种方法:

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

这仅适用于NTFS卷。

答案 1 :(得分:1)

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

在这种情况下,c:驱动器上使用的最后一条路径为c:\。因此,在打开c:时,您最终会打开c:\

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

答案 2 :(得分:1)

打开驱动器需要驱动器名称,例如“\\。\ PhysicalDrive0”。查找驱动器名称需要QueryDosDevice()。 Windows允许这样做的几率是fairly minimal