Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Folder protection for Windows using C# and concepts on Windows Shell menu for folders

4.07/5 (86 votes)
11 May 2012CPOL8 min read 51   36.1K  
Unique folder protection that issues Windows Class IDS to protect folders.

Introduction

This article is based on a concept that will make you use your own Windows platform in somewhat a better way. I am introducing a new concept called folder locking.

Generally, for everyone, it is a common topic to know how to lock and secure your folders from others. This issue really burns lots of heads. Here I will try to make you understand the issue of locking your folders in Windows. I think everyone will appreciate my post.

Background

The article can be used by novice users because it is totally built for users who don't know much about computers. This project uses Class IDS that can be found in the Registry to identify programs, and I will associate those class IDs to the folders to make them hidden from others.

Using the code

To use the code, you must know .NET. I am using C# to make my project. It is a Windows based application made in C#. The logic of taking the default names (like textbox1,Radiobutton1, etc.) is to make this project simple. If anyone wants an update, I will definitely change the names.

C#
//Form 1 of Unique folder protection
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace FolderProtection
{
    public partial class frmMain : Form
    {
        public string status;
        //bool flag = true;
        string[] arr;
        private string _pathkey;
        public frmMain()
        {
            InitializeComponent();
            arr = new string[6];
            status = "";
            arr[0] = ".{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}";
            arr[1] = ".{21EC2020-3AEA-1069-A2DD-08002B30309D}";
            arr[2] = ".{2559a1f4-21d7-11d4-bdaf-00c04f60b9f0}";
            arr[3] = ".{645FF040-5081-101B-9F08-00AA002F954E}";
            arr[4] = ".{2559a1f1-21d7-11d4-bdaf-00c04f60b9f0}";
            arr[5] = ".{7007ACC7-3202-11D1-AAD2-00805FC1270E}";
        }
        public string pathkey
        {
            get { return _pathkey; }
            set { _pathkey=value; }
        }
         private void btnSet_Click(object sender, EventArgs e)
        {
            if (rWLock.Checked)
                status = arr[0];
            else if (rCtrlPan.Checked)
                status = arr[1];
            else if (rWebBrow.Checked)
                status = arr[2];
            else if (rRclbin.Checked)
                status = arr[3];
            else if (rHlpSprt.Checked)
                status = arr[4];
            else if (rNetw.Checked)
                status = arr[5];

            if (fldrDialog.ShowDialog() == DialogResult.OK)
            { 
                
                DirectoryInfo d = new DirectoryInfo(fldrDialog.SelectedPath);
                string selectedpath = d.Parent.FullName + d.Name;
                if (fldrDialog.SelectedPath.LastIndexOf(".{") == -1)
                {
                    if (chkPasswd.Checked)
                        setpassword(fldrDialog.SelectedPath);
                    if (!d.Root.Equals(d.Parent.FullName))
                    d.MoveTo(d.Parent.FullName + "\\" + d.Name + status);
                    else d.MoveTo(d.Parent.FullName + d.Name + status);
                    txtPath.Text = fldrDialog.SelectedPath;
                    picStat.Image = Image.FromFile(Application.StartupPath + "\\lock.jpg");
                }
                else
                {
                    status = getstatus(status);
                    bool s=checkpassword();
                    if (s)
                    {
                        File.Delete(fldrDialog.SelectedPath + "\\p.xml");
                        d.MoveTo(fldrDialog.SelectedPath.Substring(0, 
                                 fldrDialog.SelectedPath.LastIndexOf(".")));
                        txtPath.Text = fldrDialog.SelectedPath.Substring(
                           0, fldrDialog.SelectedPath.LastIndexOf("."));
                        picStat.Image = Image.FromFile(Application.StartupPath + "\\unlock.jpg");
                    }
                }
            }
        }
        
        private bool checkpassword()
        {
            XmlTextReader read;
            if(pathkey ==null)
            read = new XmlTextReader(fldrDialog.SelectedPath + "\\p.xml");
            else
            read = new XmlTextReader(pathkey + "\\p.xml");
            if (read.ReadState == ReadState.Error)
                return true;
            else
            {
                try
                {
                    while (read.Read())
                        if (read.NodeType == XmlNodeType.Text)
                        {
                            checkpassword c = new checkpassword();
                            c.pass = read.Value;
                            if (c.ShowDialog() == DialogResult.OK)
                            {
                                read.Close();
                                return c.status;
                            }

                        }
                }
                catch { return true; }
                
            }
            read.Close();
            return false;
        }

        private Boolean setpassword(string path)
        {
            frmPassword p = new frmPassword();
            p.path = path;
            p.ShowDialog();
            return true;
        }
        private string getstatus(string stat)
        {
            for (int i = 0; i < 6; i++)
                if (stat.LastIndexOf(arr[i]) != -1)
                    stat = stat.Substring(stat.LastIndexOf("."));
            return stat;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (this.pathkey != null)
            {
                
                    DirectoryInfo d = new DirectoryInfo(pathkey);
                    string selectedpath = d.Parent.FullName + d.Name;
                    if (pathkey.LastIndexOf(".{") == -1)
                    {
                        txtPath.Text=pathkey;
                        DialogResult r;
                        r = MessageBox.Show("Do You want to set password ? ", 
                                 "Question?", MessageBoxButtons.YesNo);
                        if (r == DialogResult.Yes)
                        {
                            setpassword(pathkey);
                        }
                        status = arr[0];
                        if (!d.Root.Equals(d.Parent.FullName))
                            d.MoveTo(d.Parent.FullName + "\\" + d.Name + status);
                        else d.MoveTo(d.Parent.FullName + d.Name + status);
                        picStat.Image = Image.FromFile(Application.StartupPath + "\\lock.jpg");
                    }
                    else
                    {
                    status = getstatus(status);
                    bool s=checkpassword();
                    if (s)
                    {
                        File.Delete(pathkey + "\\p.xml");
                        d.MoveTo(pathkey.Substring(0, pathkey.LastIndexOf(".")));
                        txtPath.Text = pathkey.Substring(0, pathkey.LastIndexOf("."));
                        picStat.Image = Image.FromFile(Application.StartupPath + "\\unlock.jpg");
                    }
                }
            }
        }
   }
}

The above code is placed in Form1 of the current project. To do this project, first of all, start an application by choosing Windows Application, and place some radiobuttons on the form. Those radiobuttons will lock your folder appropriately to their respective class IDs. The class IDs automatically register components that are installed on any Windows system. You can get class IDs from the Windows registry. Find help regarding CLSIDs from my blog at http://windowstricks.spaces.live.com.

This form has a checkbox called Set Password, which is checked automatically. If you want to disable the locking feature to lock your folder, just uncheck this one.

Next to this, choosing the folder from the button, it will open a dialog box to choose your folder, and it will be locked.

To describe the coding: after the form is opened, it will assign the appropriate class IDs to an array called arr. Whenever the user clicks the button, it will open the file browser dialog box. Based on the radiobutton, the clsid will be assigned to a variable called status. After choosing the appropriate folder, if it is not already locked, it will lock it by renaming the folder with the extension of the class IDs. The folder will not open anymore.

Take a look at the snapshots:

Screenshot - cool_image4.jpg

The Set Password function will open up a new form called password, to set the password. To set the password, I have used a technique. I have made an XML file just within the folder and named it p.xml. If the folder already has this file, it will be overwritten. So please make sure that there is no file within the folder named p.xml.

To unlock the folder, you have to again choose the folder using the folderdialog box, in this case, I have called a function called getstatus, which will browse through all the clsids and choose the appropriate one from them. And then it will rename the folder accordingly. Have a look at the snapshot below:

Screenshot - cool_image2.jpg

If the folder is locked using a password, it will open up a new form called checkpassword. This form will read the XML file within the folder and verify the password given on the textbox. If it is correct, the function will return true, otherwise it will return false. The code for this form will look like:

C#
//Check password dialog box...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace FolderProtection
{
    public partial class checkpassword : Form
    {
        public string pass;
        public bool status;
        public checkpassword()
        {
            status = false;
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtPassword.Text.Equals(pass))
            {
                status = true;
                this.Close();
            }
            else
            {
                MessageBox.Show("Incorrect Password!!", 
                     "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                status = false;
            }
           
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

The password is set automatically from form1 to a variable called pass. It will check both of them and send a boolean value to the caller. Take a look at the snapshot below:

Screenshot - cool_image3.jpg

To set the password, I have used another form called password. It will create the XML file within the folder. Take a look at the code of that form:

C#
//Password Entry dialog box... 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace FolderProtection
{
    public partial class frmPassword : Form
    {
        public string path;
        public frmPassword()
        {
            InitializeComponent();
     
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtPassword.Text.Equals(txtReenter.Text) && txtPassword.Text.Length !=0 )
            {
                XmlDocument xmldoc = new XmlDocument();
                XmlElement xmlelem;
                XmlNode xmlnode;
                XmlText xmltext;
                xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
                xmldoc.AppendChild(xmlnode);
                xmlelem = xmldoc.CreateElement("", "ROOT", "");
                xmltext = xmldoc.CreateTextNode(txtPassword.Text);
                xmlelem.AppendChild(xmltext);
                xmldoc.AppendChild(xmlelem);
                xmldoc.Save(path + "\\p.xml");
                this.Close();
            }
            else
            {
                MessageBox.Show("Two text do not match or Blank Password", "Error");
                txtPassword.Clear();
                txtReenter.Clear();
                txtPassword.Focus();
            }
        }
    }
}

This form will create a file on the same location as the path set from form1 and read the password and set write in the root tag.

To unlock the folder, choose the already locked folder and the picturebox will assure you if it is successfully unlocked or not. A successful unlock will load the picture below.

Unique_Folder_Protection/cool_image9.jpg

In program.cs, we made the part which will be included for the context menu. Check out the code below:

C#
//Program.cs first to open... 
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace FolderProtection
{
    static class Program
    {
        /// <summary>
        ///Application will Check if it is opened 
        ///from Context menu or not and place the path accordingly
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
           
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            frmMain f = new frmMain();
            if (args.Length > 0)
                f.pathkey = args[0];
            Application.Run(f);
        }
    }
}

In this code I have assigned the path key with any argument that comes from the command line of main. In general, if I open the software from the Run menu, there will not be any argument passed as an argument if we do not explicitly send it from there. This argument will come handy when using the shell context menu. Whenever we open this software from the context menu of the folders, it will take the path in the arguments. For that I needed to include some Registry entries. Check out the images below.

Run menu option

Screenshot - cool_image7.jpg

In the above image it is shown that while creating the installer, I have made a Registry key in HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\lock.exe.

This key will be used to create an option in the Run menu. The string path is taken as [TARGETDIR]FolderProtection.exe, so when I call lock.exe from the Run menu, it will be calling the file installed in your machine. TARGETDIR will give you the exact installation folder chosen.

Shell context menu

To make a shell context menu called Unique Folder protection, I have made a Registry entry as:

Screenshot - cool_image8.jpg

HKEY_CLASSES_ROOT\Folder\Shell\Unique Folder Lock\command

This will create a new option for right clicking on any folder as a unique folder lock. After that, in the command, it will open [TARGETDIR]Folderprotection.exe %1, so while we choose this option, it will open up the exe. The %1 defines that when it opens up the software, it will take the path of the folder chosen as the argument. The argument will be taken to the pathkey for use in program.cs.

The complete original source can be downloaded from the link below:

Open the solution and you will get everything within it.

Instruction to use this software

For novice users, it is very handy to use this software. Please download the installer from the link below and install it according to the instructions given below:

First download the software from the link: Download demo - 427 KB. To install this software, please run "Protection.msi". This will ask for components, which may require an Internet connection sometimes. After the installation procedure is over, you will not find any icon over the desktop nor will you get any links in the Start menu.

To run this application

Go to Start-> Run, then type Lock.exe. The application will open up and you can use it. Have a look at the snapshot below:

Screenshot - cool_image5.jpg

Note: To lock or unlock, just use Start - > Run to open the software. You will not find link to the programs from the Start menu.

Update to installer

I have also added the software to the Windows shell menu. Take a look at the snapshot below:

Screenshot - cool_image6.jpg

To open the software you only need to go to "Unique Folder Lock" from the menu.. Try downloading this link for this option please.

Next update

In my early installer, it just opens the software, where you need to choose the folder again. In this update, it will dynamically lock or unlock your folders. Check out the new links below:

Points of interest

This project uses Windows registered class IDs. You can get your own from the Registry. I have made this software for Windows, so it will not run on any other platform. Also some of the clsids may not work in your computer. If that is the case, I am sure you can make changes to this software. But for novice users, try using the options called Control Panel or Recycle Bin, if your Operating System is other than Windows XP or later. I think you can definitely find this software handy.

If you want more help on clsid or this software, you can look at my blog at http://windowstricks.spaces.live.com, or feel free to write to me at abhishek.sur@gmail.com or abhi2434@yahoo.com. Thank you.

History

Update 1: This is my first update. Hoping for positive replies to this article. I need your appreciation friends. Also let me know if the software is bug free or not.

Thank you very much for reading this article.

Update 2: In this update, I have made some changes to the installer. Check out.

Update 3: In this update I have added the context menu part of the installer, so that you can click on the context menu of Windows shell to choose a folder.

Update 4: In this update, I have modified the project so that some of the bugs of my early release could be removed. Now you can dynamically choose any folder from your harddrive and the software will ask for passwords.

Please send feedback to me on how you see my articles. A future modification is due. Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)