using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace FolderDrive_Mapper
{
#region //API Drive Flags
public enum dFlags
{
DDD_EXACT_MATCH_ON_REMOVE = 4,
DDD_NO_BROADCAST_SYSTEM = 8,
DDD_RAW_TARGET_PATH = 1,
DDD_REMOVE_DEFINITION = 2,
}
#endregion
static class DriveMount
{
#region //API Stuff
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool DefineDosDevice(dFlags dwflags, string lpDeviceName, string path);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);
#endregion
#region //Map Or Unmap Drives
public static void MapDrive(string DriveAddr, string path)
{
try
{
if (ConfirmAction(GetDriveLetter(DriveAddr)))
{
if (!DefineDosDevice(0, GetDriveLetter(DriveAddr), path))
throw new Win32Exception("An error occurred while trying to map the drive");
}
}
catch (Win32Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static void UnmapDrive(string DriveAddr)
{
try
{
if (ConfirmAction(GetDriveLetter(DriveAddr)))
{
if (!DefineDosDevice(dFlags.DDD_REMOVE_DEFINITION, GetDriveLetter(DriveAddr), null))
throw new Win32Exception("An error occurred while trying to unmap the drive");
}
}
catch (Win32Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region //Check If Drive Mapped
public static bool IsDriveMapped(string DriveAddr)
{
StringBuilder sb = new StringBuilder(259);
if (QueryDosDevice(GetDriveLetter(DriveAddr), sb, sb.Capacity) == 0)
{
// Return empty string if the drive is not mapped
if (Marshal.GetLastWin32Error() == 2) return false;
throw new Win32Exception();
}
return true;
}
#endregion
#region //Get Drive Letter
public static string GetDriveLetter(string DriveAddr)
{
return char.ToUpper(DriveAddr[0]) + ":";
}
#endregion
#region //Confirm Action On Drive Letter
private static bool ConfirmAction(string DriveLetter)
{
return (MessageBox.Show("Are you sure you want to take the specified action on " + DriveLetter + "?","Confirm Action",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk) == DialogResult.Yes) ? true : false;
}
#endregion
}
}