How to Lock And Unlock a Folder through Code in VB.NET

This code can be used to lock and unlock a selected folder.It mainly used for authentication purpose. 1.Make a window form which contains a textbox named as txtbxBrowseFolderName,3 buttons names as btnBrowse, btnLock, btnUnlock. 2.Insert FolderBrowserDialog1 control..

3.Insert the following Namespace

(a)Imports System.Security.AccessControl (b)Imports System.IO 4.Then insert the following piece of code.

PrivateSub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click

With FolderBrowserDialog1

If .ShowDialog() = DialogResult.OK Then

txtbxBrowseFolderName.Text = .SelectedPath

EndIf

EndWith

EndSub
PrivateSub btnLock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLock.Click

Dim fs AsFileSystemSecurity = File.GetAccessControl(txtbxBrowseFolderName.Text)

fs.AddAccessRule(NewFileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))

File.SetAccessControl(txtbxBrowseFolderName.Text, fs)

EndSub
PrivateSub btnUnlock_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUnlock.Click

Dim fs AsFileSystemSecurity = File.GetAccessControl(txtbxBrowseFolderName.Text)

fs.RemoveAccessRule(NewFileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))

File.SetAccessControl(txtbxBrowseFolderName.Text, fs)

EndSub

5.Now you can choose a folder that you want to lock .then click the lock button.

6.Then you can test it by clicking the folder manumally it will show you a message that you are unable to access the folder.

7.For accessing the folder again you need to unlock the folder.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!