FileInfo.Encrypt 方法

定义

将某个文件加密,使得只有加密该文件的帐户才能将其解密。

C#
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public void Encrypt ();
C#
public void Encrypt ();
C#
[System.Runtime.InteropServices.ComVisible(false)]
public void Encrypt ();
属性

例外

指定了无效的驱动器。

找不到当前 FileInfo 对象描述的文件。

打开文件时发生 I/O 错误。

文件系统不是 NTFS。

当前操作系统不是 Microsoft Windows NT 或更高版本。

当前 FileInfo 对象描述的文件为只读文件。

- 或 -

当前平台不支持此操作。

调用方没有所要求的权限。

示例

下面的代码示例使用 Encrypt 方法和 Decrypt 方法加密文件,然后将其解密。

C#
using System;
using System.IO;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileExample
    {
        public static void 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 (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        public static void AddEncryption(string FileName)
        {
            // Create a new FileInfo object.
            FileInfo fInfo = new FileInfo(FileName);
            if (!fInfo.Exists)
            {
                //Create the file.
                fInfo.Create();
            }
            // Add encryption.
            fInfo.Encrypt();
        }

        public static void RemoveEncryption(string FileName)
        {
            // Create a new FileInfo object.
            FileInfo fInfo = new FileInfo(FileName);
            if (!fInfo.Exists)
            {
                //Create the file.
                fInfo.Create();
            }
            // Remove encryption.
            fInfo.Decrypt();
        }
    }
}

//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

注解

方法 Encrypt 允许加密文件,以便只有用于调用此方法的帐户才能解密该文件。 Decrypt使用 方法解密由 Encrypt 方法加密的文件。

Encrypt方法和 Decrypt 方法都使用安装在计算机上的加密服务提供程序 (CSP) ,以及调用方法的进程的文件加密密钥。

当前文件系统的格式必须为 NTFS,并且当前操作系统必须是 Microsoft Windows NT 或更高版本。

适用于

产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1