creating virtual hard Drive
how can I create Virtual Hard Drive (开发者_JAVA技巧like Z:) that store it's files on physical hard drive (Like C:\Files).
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:\temp");
Console.WriteLine(Subst.GetDriveMapping('z'));
Subst.UnmapDrive('z');
You can use subst command. Use System.Diagnostic.Process to run the subst.exe with desired parameters.
Here is the command syntax:
Syntax
Associates a path with a drive letter.
SUBST [drive1: [drive2:]path] SUBST drive1: /D
drive1: Specifies a virtual drive to which you want to assign a path.
[drive2:]path Specifies a physical drive and path you want to assign to a virtual drive.
/D Deletes a substituted (virtual) drive.
Type SUBST with no parameters to display a list of current virtual drives.list of current virtual drives.
Do it the exact same way you would map a network drive, but point it to a folder on the current machine. The only thing you have to do special is use a UNC path for the local folder.
Here is a helper class
Not sure how to do this in C# but this should help you:
Ive just tested this and works perfect
On my computer have 1 hard drive devised into 2, C:
& D:
, going into D:
i have a folder called Backup, if you right click the folder and click the Share
Tab, you will see Network Path
.. On my pc it looks like \\Robert-home\backup
I then proceeded to CMD
and executed the following command
NET USE Z: \\Robert-home\backup
Witch successfully map the contents of D:\backup
to Z:
Im sure you can complete such a task within C#..
I usually use this method at work for client support to transfer and backup files before new consoles are issued to them.
精彩评论