This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 2.0+

Encrypting and Decrypting Files

The Microsoft Windows operating system's New Technology File System (NTFS) includes the facility to encrypt files to reduce the risk that their contents are seen by unauthorised people. The encryption status of files can be controlled via .NET.

Encrypted Files

When Microsoft introduced Windows NT, the new operating system included the option for an improved file system. This file system, known as New Technology File System (NTFS), added many benefits for both professional and home users. The changes included extra security, larger volume sizes and improved reliability.

One of the features of NTFS is the ability to transparently encrypt files. Where the operating system version supports it, a user can open the Properties dialog box for a file or folder and encrypt it by simply clicking a checkbox. The files are encrypted using an encryption certificate that is linked to the current user. The user performing the encryption can open the files as normal without providing additional credentials. Other users, or those that have obtained the files without authorisation, cannot easily decrypt the files and access their contents.

Encrypting Files

In a previous article I described how similar file attributes can be obtained and changed using the SetAttributes and GetAttributes methods of the File class. Although you can use these to check for encryption, you can't user SetAttributes to actually encrypt or decrypt files. Instead, you must use separate methods created for this purpose.

The methods are static methods of the File class, which resides in the System.IO namespace. To simplify access to the type, add the following using directive to your code:

using System.IO;

To encrypt a file, use the Encrypt method. This has a single parameter, which is used to specify the path of the file to be encrypted. You can also specify the path to a folder, in which case all new files added to the folder will be encrypted automatically.


When you execute the above statement on a system that has not yet used file encryption, a warning will be displayed that the generated encryption certificate should be backed up. This is important, as the certificate will be required to recover encrypted files if they must be accessed by a different user. For example, following a reinstallation of the operating system after a failure.

Decrypting Files

If you wish to remove encryption from a file or folder programmatically, you can use the Decrypt method. Again, you must provide the path of the item being decrypted.

15 March 2013