Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 11 May 2012
Rate this:
Please Sign up or sign in to vote.
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.

//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:

//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:

//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:

//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)

Share

About the Author

Abhishek Sur
Architect
India India
Did you like his post?
 
Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.
 
Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook
 
Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.
 
Presently he is working in WPF, a new foundation to UI development, but mostly he likes to work on architecture and business classes. ASP.NET is one of his strength as well.
Have any problem? Write to him in his Forum.
 
You can also mail him directly to abhi2434@yahoo.com
 
Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com
 
Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing
Follow on   Twitter   Google+

Comments and Discussions

 
Questionhow to use tool folder lock PinmemberMember 106302591-Sep-14 23:27 
GeneralYour code not much efficient Pinmemberpinna3-Jun-14 7:13 
QuestionProblem With Your Tool Pinmemberashis1368-May-14 2:47 
Questionfrmpassword P = new frmpassword(); PinmemberMember 1051260928-Jan-14 16:26 
QuestionFolder Lock Issue Pinmemberbhardwaz4-Dec-13 0:43 
QuestionVery clever but... PinmemberMember 302311521-Oct-13 8:52 
QuestionMy Vote Pinmembervmdhartec13-Oct-13 3:37 
Generalcmd PinmemberDhruv Shah0072-Oct-13 20:19 
QuestionVote 5 Pinmemberparkavikarthi19-Sep-13 20:57 
GeneralMy vote of 3 PinmemberJeepers8130-May-13 21:13 
GeneralMy vote of 5 Pinmembermaximochen25-Apr-13 7:59 
Questionhave a issue! PinmemberMaster Ab21-Apr-13 13:52 
QuestionFolder protection for Windowsusing C# and concepts onWindows Shell menu for folders Pinmembernickalcala27-Mar-13 21:09 
GeneralMy vote of 5 Pinmembernileshsironja10-Mar-13 2:07 
GeneralMy vote of 3 Pinmemberbiswas sanjib28-Jan-13 18:36 
GeneralMy vote of 5 PinmemberSergey Lapp18-Dec-12 18:12 
GeneralMy vote of 3 PinmvpDave Kreskowiak1-Nov-12 2:23 
GeneralMy vote of 5 PinmemberHammad Raza18-Oct-12 2:26 
QuestionCan you give me the sample code for the same in MFC Pinmemberpradeep_done18-Sep-12 15:59 
GeneralMy vote of 5 Pingroupss9o9o9o13-Sep-12 1:05 
GeneralMy vote of 5 Pinmembergeekbond19-Jun-12 3:19 
GeneralMy vote of 5 Pinmemberfredatcodeproject3-Jun-12 4:35 
QuestionHow to create password protected folders using C# PinmemberSuman Dandala29-May-12 3:16 
BugRename the folder Cracks the lock Pinmemberdwesley isaac25-May-12 2:43 
GeneralMy vote of 4 PinmemberFrewCen11-May-12 23:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 11 May 2012
Article Copyright 2007 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid