FileInfo.Decrypt Method ()

 

Decrypts a file that was encrypted by the current account using the Encrypt method.

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)

<ComVisibleAttribute(False)>
Public Sub Decrypt

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 Decrypt method allows you to decrypt a file that was encrypted using the Encrypt method. The Decrypt method can decrypt only files that were encrypted using the current user account.

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 and then decrypt a file.

Imports System
Imports System.IO
Imports System.Security.AccessControl



Module FileExample

    Sub Main()
        Try
            Dim FileName As String = "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 e As Exception
            Console.WriteLine(e)
        End Try

    End Sub



    Sub AddEncryption(ByVal FileName As String)
        ' Create a new FileInfo object.
        Dim fInfo As New FileInfo(FileName)
        If fInfo.Exists = False Then
            fInfo.Create()
        End If
        ' Add encryption.
        fInfo.Encrypt()

    End Sub



    Sub RemoveEncryption(ByVal FileName As String)
        ' Create a new FileInfo object.
        Dim fInfo As New FileInfo(FileName)
        If fInfo.Exists = False Then
            fInfo.Create()
        End If
        ' Remove encryption.
        fInfo.Decrypt()

    End Sub
End Module
'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

FileIOPermission

Associated enumerations: Read, Write

Security action: Demand.

For permission to read and write to the file described by the current FileInfo object.

.NET Framework
Available since 2.0
Return to top
Show: