[C#] FolderDrive Mapper - Developed by AceInfinity

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
FolderDrive Mapper

Video:

Preview:
hrCEc.png


Description:
Easily map a folder to as a virtual drive with it's own drive letter on your machine, or unmap a drive letter.

Source:

Form1.cs
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;

namespace FolderDrive_Mapper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.AllowDrop = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        #region Drag Drop Filepath
        private void textBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
        }

        private void textBox1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string MyFile = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                textBox1.Text = MyFile;
            }
        }
        #endregion

        #region //Map Drive
        private void button1_Click(object sender, EventArgs e)
        {
            if (Functions.ValidInputs(textBox1.Text, textBox2.Text, true))
            {
                if (!DriveMount.IsDriveMapped(textBox2.Text))
                {
                    DriveMount.MapDrive(textBox2.Text, @textBox1.Text);
                }
                else
                {
                    MessageBox.Show("Drive letter already mapped, please unmap this drive letter first.",
                        "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }           
        }
        #endregion

        #region //Unmap Drive
        private void button2_Click(object sender, EventArgs e)
        {
            if (Functions.ValidInputs(textBox1.Text, textBox2.Text, false))
            {
                if (DriveMount.IsDriveMapped(textBox2.Text))
                {
                    DriveMount.UnmapDrive(textBox2.Text);
                }
                else
                {
                    MessageBox.Show("Drive letter already unmapped.",
                        "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }           
        }
        #endregion

        private void button3_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fbd = new FolderBrowserDialog())
            {
                fbd.Description = "Browse for a folder location that you wish to mount as a new virtual drive...";
                fbd.RootFolder = Environment.SpecialFolder.DesktopDirectory;
                fbd.ShowNewFolderButton = true;
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    textBox1.Text = fbd.SelectedPath;
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", ",");
        }

    }
}

DriveMount.cs
Code:
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
    }
}

Functions.cs
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace FolderDrive_Mapper
{
    class Functions
    {
        #region //Check Valid Inputs
        public static bool ValidInputs(string MainDir, string DriveLetter, bool CheckPath)
        {
            if (CheckPath)
            {
                if (!Directory.Exists(MainDir)) { return false; }
            }

            if (DriveLetter.Length == 2 && Char.IsLetter(DriveLetter[0]) && DriveLetter[1] == ':'))
            {
                return true;
            }
            MessageBox.Show("There was an invalid input specified, please make sure that you type everything in correctly!", "Invalid Input",
                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            return false;
        }
        #endregion
    }
}
 
Last edited:
I share the source just so that people can learn how it works if they don't benefit from using it. Thankyou :)
 
Hi, I have tried abve code, it works for normal users. But when i run the application in Admnin mode, the drive wont get created. Can you please suggest something regarding this. Thanks in advance
 
Hi, I have tried abve code, it works for normal users. But when i run the application in Admnin mode, the drive wont get created. Can you please suggest something regarding this. Thanks in advance
Welcome to Sysnative!

There is some advice here regarding this: Virtual Disk Drivers, UAC and NT

Does it help at all?
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top