FileInfo::Encrypt Method ()
Encrypts a file so that only the account used to encrypt the file can decrypt it.
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| DriveNotFoundException | An invalid drive was specified. |
| FileNotFoundException | The file described by the current FileInfo object could not be found. |
| IOException | An I/O error occurred while opening the file. |
| NotSupportedException | The file system is not NTFS. |
| PlatformNotSupportedException | The current operating system is not Microsoft Windows NT or later. |
| UnauthorizedAccessException | The file described by the current FileInfo object is read-only. -or- This operation is not supported on the current platform. -or- The caller does not have the required permission. |
The Encrypt method allows you to encrypt a file so that only the account used to call this method can decrypt it. Use the Decrypt method to decrypt a file encrypted by the Encrypt method.
Both the Encrypt method and the Decrypt method use the cryptographic service provider (CSP) installed on the computer and the file encryption keys of the process calling the method.
The current file system must be formatted as NTFS and the current operating system must be Microsoft Windows NT or later.
The following code example uses the Encrypt method and the Decrypt method to encrypt a file and then decrypt it.
using namespace System; using namespace System::IO; using namespace System::Security::AccessControl; static void Addencryption(String^ fileName) { // Create a new FileInfo object. FileInfo^ fInfo = gcnew FileInfo(fileName); if (!fInfo->Exists) { fInfo->Create(); } // Add encryption. fInfo->Encrypt(); } static void Removeencryption(String^ fileName) { // Create a new FileInfo object. FileInfo^ fInfo = gcnew FileInfo(fileName); if (!fInfo->Exists) { fInfo->Create(); } // Remove encryption. fInfo->Decrypt(); } int main() { try { String^ fileName = "c:\\MyTest.txt"; Console::WriteLine("Encrypt " + fileName); // Encrypt the file. Addencryption(fileName); Console::WriteLine("Decrypt " + fileName); // Decrypt the file. Removeencryption(fileName); Console::WriteLine("Done"); } catch (IOException^ ex) { Console::WriteLine(ex->Message); } } //This code produces output similar to the following; //results may vary based on the computer/file structure/etc.: // //Encrypt c:\MyTest.txt //Decrypt c:\MyTest.txt //Done
Available since 2.0