
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
748
|
Chapter 12: Filesystem I/O
12.27 Encrypting/Decrypting an Existing File
Problem
You need a simple way to encrypt an existing file on the filesystem so that only the
account used to encrypt the file can decrypt it.
Solution
Use the Decrypt and Encrypt methods of the File class:
public static void EncryptFile(string fileName)
{
File.Encrypt(fileName);
}
public static void DecryptFile(string fileName)
{
File.Decrypt(fileName);
}
Discussion
Both the Encrypt and Decrypt methods of the File class accept a single parameter, a
file path/name, and return a
void. The filename parameter must be a valid path and
name. The result of calling the
Encrypt method is an encrypted file that can be unen-
crypted only by the user who encrypted it in the first place. Calling the
Decrypt
method decrypts the file.
The
Encrypt method is a wrapper around the EncryptFile method in the unmanaged
Advapi32.dll, and the
Decrypt method is a wrapper around the DecryptFile method,
also in Advapi32.dll. These underlying methods require exclusive access to the file
that is being encrypted/decrypted. This means that no other process may be cur-
rently accessing this file when the
Encrypt/Decrypt methods are called. Also be aware
that the filesystem must be NTFS or a
NotSupportedException will be thrown by the
Encrypt/Decrypt method. ...