Clipboard API uses OLE internally and thus can only be called on a STA thread. Unlike WinForms applications, console applications aren't using STA by default.
Add the [STAThread]
attribute to Main
:
[STAThread]
static void Main(string[] args)
{
...
Just do what the exception message told you to:
Unhandled Exception:
System.Threading.ThreadStateException
: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function hasSTAThreadAttribute
marked on it.
Cleaning up your program a bit:
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;
}
}
}
}
This has several advantages over your program:
- It doesn't need to load the whole file into RAM at the same time
- It returns the correct result if the file contains non-ASCII characters/bytes
- It'd shorter and cleaner