如何创建将其文件存储在物理硬盘上的虚拟硬盘(如Z:)(如C:\Files)。

最佳答案

这是直接执行此操作的C#代码:

using System;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;

static class Subst {
    public static void MapDrive(char letter, string path) {
        if (!DefineDosDevice(0, devName(letter), path))
            throw new Win32Exception();
    }
    public static void UnmapDrive(char letter) {
        if (!DefineDosDevice(2, devName(letter), null))
            throw new Win32Exception();
    }
    public static string GetDriveMapping(char letter) {
        var sb = new StringBuilder(259);
        if (QueryDosDevice(devName(letter), sb, sb.Capacity) == 0) {
            // Return empty string if the drive is not mapped
            int err = Marshal.GetLastWin32Error();
            if (err == 2) return "";
            throw new Win32Exception();
        }
        return sb.ToString().Substring(4);
    }


    private static string devName(char letter) {
        return new string(char.ToUpper(letter), 1) + ":";
    }
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool DefineDosDevice(int flags, string devname, string path);
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int QueryDosDevice(string devname, StringBuilder buffer, int bufSize);
}

用法示例:
        Subst.MapDrive('z', @"c:\temp");
        Console.WriteLine(Subst.GetDriveMapping('z'));
        Subst.UnmapDrive('z');

关于c# - 创建虚拟硬盘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3753758/

10-12 01:24