Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

c# - creating virtual hard Drive

how can I create Virtual Hard Drive (like Z:) that store it's files on physical hard drive (Like C:Files).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is C# code to do this directly:

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);
}

Sample usage:

        Subst.MapDrive('z', @"c:emp");
        Console.WriteLine(Subst.GetDriveMapping('z'));
        Subst.UnmapDrive('z');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...