1

对 C# 非常陌生 - 从 Powershell 和 Java 中的真正管理员迁移。我正在使用 MS 功能来解密文件:

static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
    {
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        //A 64 bit key and IV is required for this provider.
        //Set secret key For DES algorithm.
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        //Set initialization vector.
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

        //Create a file stream to read the encrypted file back.
        FileStream fsread = new FileStream(sInputFilename,
           FileMode.Open,
           FileAccess.Read);
        //Create a DES decryptor from the DES instance.
        ICryptoTransform desdecrypt = DES.CreateDecryptor();
        //Create crypto stream set to read and do a 
        //DES decryption transform on incoming bytes.
        CryptoStream cryptostreamDecr = new CryptoStream(fsread,
           desdecrypt,
           CryptoStreamMode.Read);
        //Print the contents of the decrypted file.
        StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
        fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
        fsDecrypted.Flush();
        fsDecrypted.Close();
    }

目前,我通过各种不同的形式在各​​种按钮中调用它:

        string decryptionKey = File.ReadAllText(@"C:\ThickClient\secretKey.skey");
        DecryptFile("C:\\ThickClient\\Encrypted.enc", "C:\\ThickClient\\tempPWDump.enc", decryptionKey);
        string decryptedPW = File.ReadAllText(@"C:\ThickClient\tempPWDump.enc");
        File.Delete(@"C:\ThickClient\tempPWDump.enc");

而且我必须在每个表单中定义static void DecryptFile {code},并在每个表单中将其调用为一个新变量以使用它。看起来很疯狂,我可以在 Windows 窗体的哪个位置定义它并设置一个全局变量,以便它可用于每个窗体?

4

1 回答 1

5

使用公共静态类。为此,请右键单击项目并选择添加 → 类。在对话框中给出诸如“Utils.cs”之类的名称并确认。将代码更改为如下所示:

public static class Utils
{
    public static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
    {
        //...
    }
}

现在,在项目的任何地方,以任何形式,您都可以拥有:

Utils.DecryptFile(...);

如果您有多个项目,它会变得有点复杂,但仍然非常简单。只需将该类放入类库类型的新项目中,然后在需要实用程序的任何地方添加对该项目的引用。

附带说明一下,要使变量公开可用,只需在上面的类中添加类似的内容:(称为静态 getter)

private static string decryptedPW = "";
public static string DecryptedPW
{
    get
    {
        //need to initialize?
        if (decryptedPW.Length == 0)
        {
            string filePath = @"C:\ThickClient\tempPWDump.enc";
            decryptedPW = File.ReadAllText(filePath);
            File.Delete(filePath);
        }
        return decryptedPW;
    }
}

然后从项目中的任何地方访问它:

string decryptedPW =  Utils.DecryptedPW;
于 2013-09-15T11:03:56.653 回答