0

ファイルをそれぞれの .exe にドラッグするコンソールまたはフォームを作成しようとしています。プログラムはそのファイルを取得してハッシュし、クリップボードのテキストを以前に生成されたハッシュに設定します。

これは私のコードです

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        string path = args[0];          
        StreamReader wer = new StreamReader(path.ToString());
        wer.ReadToEnd();
        string qwe = wer.ToString();
        string ert = Hash(qwe);
        string password = "~" + ert + "~";
        Clipboard.SetText(password);
    }

    static public string Hash(string input)
    {
        MD5 md5 = MD5.Create();
        byte[] inputBytes = Encoding.ASCII.GetBytes(input);
        byte[] hash = md5.ComputeHash(inputBytes);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();
    }
}
}

リリースから単一の .exe を取得してファイルをドラッグすると、ある種のスレッド エラーが発生します。vb2010 ではなくコンソールにあるため、提供できません。助けてくれてありがとう

4

1 に答える 1

0

クリップボード API は内部で OLE を使用するため、STA スレッドでのみ呼び出すことができます。WinForms アプリケーションとは異なり、コンソール アプリケーションはデフォルトで STA を使用していません。

[STAThread]に属性を追加しMainます。

[STAThread]
static void Main(string[] args)
{
    ...

例外メッセージで指示されたことを実行するだけです:

未処理の例外: System.Threading.ThreadStateException: OLE 呼び出しを行う前に、現在のスレッドをシングル スレッド アパートメント (STA) モードに設定する必要があります。Main 関数がSTAThreadAttributeマークされていることを確認します。


プログラムを少しクリーンアップします。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Windows.Forms;

namespace HashToClipboard
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            string hexHash = Hash(args[0]);
            string password = "~" + hexHash + "~";
            Clipboard.SetText(password);
        }

        static public string Hash(string path)
        {
            using (var stream = File.OpenRead(path))
            using (var hasher = MD5.Create())
            {
                byte[] hash = hasher.ComputeHash(stream);
                string hexHash = BitConverter.ToString(hash).Replace("-", "");
                return hexHash;
            }
        }
    }
}

これには、プログラムよりもいくつかの利点があります。

  • ファイル全体を同時に RAM にロードする必要はありません。
  • ファイルに非ASCII文字/バイトが含まれている場合、正しい結果が返されます
  • 短くてきれいだ
于 2013-10-25T21:31:30.363 に答える