如何在ChoPGP库PGP加密中去除原始文件路径仅保留文件名?
解决ChoPGP加密文件时嵌入完整路径的问题
ChoPGP的EncryptFile方法默认会将传入的完整文件路径作为文件名嵌入到加密后的PGP包中,要只保留文件名,可通过以下两种方式修改代码:
方法一:设置FileName属性后调用EncryptFile
先提取源文件的纯文件名,通过设置ChoPGPEncryptDecrypt实例的FileName属性,指定加密后嵌入PGP包内的文件名:
using System.IO; using (ChoPGPEncryptDecrypt pgp = new ChoPGPEncryptDecrypt()) { // 提取源文件的纯文件名 string sourceFileName = Path.GetFileName(@"\\appdevtest\c$\appstest\Transporter\test\Test.txt"); // 指定嵌入PGP包内的文件名 pgp.FileName = sourceFileName; pgp.EncryptFile(@"\\appdevtest\c$\appstest\Transporter\test\Test.txt", @"\\appdevtest\c$\appstest\Transporter\test\OSCTestFile_ChoPGP.gpg", @"\\appdevtest\c$\appstest\Transporter\pgpKey\PublicKey\atorres\atorres_publicKey.asc", true, true); }
方法二:使用流加密方式指定文件名
通过文件流读取源文件,调用Encrypt方法并显式传入纯文件名参数,更灵活地控制嵌入的文件名:
using System.IO; string sourceFilePath = @"\\appdevtest\c$\appstest\Transporter\test\Test.txt"; string destFilePath = @"\\appdevtest\c$\appstest\Transporter\test\OSCTestFile_ChoPGP.gpg"; string pubKeyFilePath = @"\\appdevtest\c$\appstest\Transporter\pgpKey\PublicKey\atorres\atorres_publicKey.asc"; // 提取纯文件名 string targetFileName = Path.GetFileName(sourceFilePath); using (FileStream inputStream = File.OpenRead(sourceFilePath)) using (FileStream outputStream = File.Create(destFilePath)) using (ChoPGPEncryptDecrypt pgp = new ChoPGPEncryptDecrypt()) { // 显式传入要嵌入的文件名 pgp.Encrypt(inputStream, outputStream, pubKeyFilePath, targetFileName, true, true); }
两种方式都能确保加密后的PGP包内仅保留Test.txt作为文件名,而不会包含完整路径。
内容的提问来源于stack exchange,提问作者Albert Torres
相关产品推荐
相关产品推荐

