File.Decrypt(String) 方法

定義

解密目前帳戶使用 Encrypt(String) 方法加密的檔案。

[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static void Decrypt(string path);
public static void Decrypt(string path);

參數

path
String

路徑,描述要解密的檔案。

屬性

例外狀況

.NET Framework 和 2.1 之前的 .NET Core 版本:參數 path 是長度為零的字串、只包含空格符,或包含一或多個無效字元。 您可以使用 GetInvalidPathChars() 方法查詢無效字元。

path 參數為 null

指定的磁碟機無效。

找不到 path 參數所描述的檔案。

開啟檔案時發生 I/O 錯誤。 例如,加密的檔案已經開啟。

-或-

這個作業在目前平台不受支援。

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。

目前的作業系統不是 Windows NT 或更新版本。

檔案系統不是 NTFS。

path 參數指定了唯讀的檔案。

-或-

這個作業在目前平台不受支援。

-或-

path 參數指定了目錄。

-或-

呼叫端沒有必要的權限。

範例

下列程式代碼範例會 Encrypt 使用 方法和 方法 Decrypt 來加密和解密檔案。 檔案必須存在,範例才能運作。

using System;
using System.IO;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileExample
    {
        public static void Main()
        {
            try
            {
                string FileName = "test.xml";

                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);
            }

            Console.ReadLine();
        }

        // Encrypt a file.
        public static void AddEncryption(string FileName)
        {

            File.Encrypt(FileName);
        }

        // Decrypt a file.
        public static void RemoveEncryption(string FileName)
        {
            File.Decrypt(FileName);
        }
    }
}

備註

方法 Decrypt 可讓您解密使用 方法加密的 Encrypt 檔案。 方法 Decrypt 只能解密使用目前用戶帳戶加密的檔案。

重要

只有能夠使用NTFS加密文件系統 (EFS) 的 Windows 平臺才支援此 API。 任何嘗試在非 Windows 系統、Windows Home Edition 系統或非 NTFS 磁碟驅動器上使用此功能,都會導致 PlatformNotSupportedExceptionNotSupportedException,視情況而定。

不建議在 .NET Core 中使用此 API;它包含在內,可針對移至 .NET Core 但仍然明確以 Windows 為目標的應用程式啟用可移植性。

方法 Decrypt 需要解密檔案的獨佔存取權,如果另一個進程正在使用檔案,則會引發例外狀況。

方法與 Decrypt 方法都會Encrypt使用安裝在計算機上的密碼編譯服務提供者 (CSP) ,以及呼叫 方法之進程的檔案加密密鑰。

目前的文件系統必須格式化為NTFS,而且目前的作業系統必須是Windows NT或更新版本。

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.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