2013-10-25 4 views
0

파일을 해당 .exe로 끌어 놓을 콘솔 또는 양식을 만들려고합니다. 프로그램에서 해당 파일을 가져 와서 해시 한 다음 클립 보드 텍스트를 가혹하게 생성 된 해시로 설정합니다. . 내가 릴리스에서 단일 .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(); 
    } 
} 
} 

입니다 콘솔에서, vb2010 않습니다. 어떤 도움 주셔서 감사합니다

+0

콘솔에서 프로그램 *을 실행하고 파일 이름을 인수로 전달하면 어떻게됩니까? 그렇게하면 전체 스택 추적을 가져와 질문에 복사하여 붙여 넣을 수 있습니다. 여러분의 코드는 어쨌든 결함이있는 것입니다. 왜냐하면 처음에는 문자열로 읽지 않아야하기 때문입니다. 대신 스트림에서'ComputeHash'를 호출하십시오. –

+0

@ Jon Skeet - 답변, 어떻게 대답 할 수 있습니까? – Dean

+0

그럼 어느 비트에 붙어 있니? –

답변

0

클립 보드 API는 내부적으로 OLE를 사용하므로 STA 스레드에서만 호출 할 수 있습니다. WinForms 응용 프로그램과 달리 콘솔 응용 프로그램은 기본적으로 STA를 사용하지 않습니다.

가 추가 [STAThread] 속성 Main에 :

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

그냥 할 예외 메시지가 당신에게 무엇을 :

처리되지 않은 예외 : System.Threading.ThreadStateException : 현재 스레드가 단일 스레드 아파트로 설정해야합니다 (STA) 모드로 전환 할 수 있습니다. 주 기능에 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가 아닌 문자/바이트가 포함 된 경우 올바른 결과를 반환합니다.
  • 더 짧고 깨끗함
관련 문제