Getting Hash from command line arguments - c#

I am trying to create a console or form where you would drag a file onto their respective .exe
The program would get that file and hash it, then set the clipboard text to the proviously generated hash.
This is my code
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();
}
}
}
When I get the single .exe from the release, and drag a file onto it, I get some sort of threading error- I can't provide it because it is in the console, not in vb2010. Thanks for any help

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 has STAThreadAttribute 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

Related

Nethereum EthECKey not working. Scripts are not compiled

If i add this line to my code then it refuses to compile!(This happens with All scripts in unity, even empty ones)
string publicKey = Nethereum.Signer.EthECKey.GetPublicAddress(privatekey);
Code:
using System.Collections;
using System;
using System.Collections.Generic;
using Nethereum.Util;
using UnityEngine;
using System.Threading.Tasks;
using Nethereum.Hex.HexConvertors.Extensions;
using Org.BouncyCastle.Crypto.Digests;
using System.Linq;
using System.Text;
using Nethereum.Util.Keccak;
using System.Numerics;
using System.Runtime.CompilerServices;
using Nethereum.RLP;
using Nethereum.Signer.Crypto;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
public class MianScript : MonoBehaviour
{
string chain = "ethereum";
string network = "rinkeby";
[SerializeField]
public string password;
public void OnClickBTN()
{
string privatekey = CreateAccount();
string publicKey = Nethereum.Signer.EthECKey.GetPublicAddress(privatekey);
Debug.Log("\nPrivate: " + privatekey + "\nPublicKey: " + publicKey);
}
public byte[] CalculateHash(byte[] value)
{
var digest = new KeccakDigest(256);
var output = new byte[digest.GetDigestSize()];
digest.BlockUpdate(value, 0, value.Length);
digest.DoFinal(output, 0);
return output;
}
public async Task<String> GetBalance(string chain1, string network1, string address1)
{
string balance = await EVM.BalanceOf(chain1, network1, address1);
return balance;
}
public static string CreateAccount()
{
System.Random random = new System.Random();
var bytes = new Byte[32];
random.NextBytes(bytes);
var hexArray = Array.ConvertAll(bytes, x => x.ToString("X2"));
var hexStr = String.Concat(hexArray);
return Convert.ToString(hexStr.ToLower());
}
}
Help pls!
I'm not using unity, C# either but it seems that GetPublicAddress() is not a static function but a class method.
So I think you need to do something like that:
// Creating an EthECKey instance
var key = new Nethereum.Signer.EthECKey(privateKey.HexToByteArray(), true);
// Getting the public Address
string publicKey = key.GetPublicAddress();
I simply checked examples from here.

how to print each line of text file using below Rx.Net code?

Problem Statement - I have a file continuously written by a process line by line. I would like a C# solution which will print line by line as soon as it is written by the process.
Solution - I would like to use Reactive extension C#, where I will subscribe the stream.
I tried below code, but how to print each line,
stream.Subscribe(e => Console.WriteLine(e.//how to print each line));
Here is full code,
using System;
using System.Collections.Generic;
using System.IO;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream(#"C:\Files\test_Copy.txt", FileMode.Open))
{
var stream = ObserveLines(fs);
stream.Subscribe(e => Console.WriteLine(e.//how to print each line));
}
}
public static IObservable<string> ObserveLines(Stream inputStream)
{
return ReadLines(inputStream).ToObservable(Scheduler.ThreadPool);
}
public static IEnumerable<string> ReadLines(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
}
}

The Namespace X already contains a definition for XX?

I don't understand this error I am getting. I have tried to clean and build my project several times. Can anyone help me?
Program.cs
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
class Program
{
static void Main(string[] args)
{
var lstWebSites = new List<string>
{
"www.mearstransportation.com",
"www.amazon.com",
"www.ebay.com",
"www.att.com",
"www.verizon.com",
"www.sprint.com",
"www.centurylink.com",
"www.yahoo.com"
};
string filename = #"RequestLog.txt";
{
using (var writer = new StreamWriter(filename, true))
{
foreach (string website in lstWebSites)
{
for (var i = 0; i < 4; i++)
{
MyWebRequest request = new MyWebRequest();
request.Request(website);
}
}
}
}
}
}
}
MyWebRequest.cs - the problem is here: public class MyWebRequest
Error is: "The namespace HttpRequestApp already contains a definition for MyWebRequest"
using HTTPrequestApp.MyWebRequest;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace HTTPrequestApp
{
public class MyWebRequest : IWebRequest
{
public void Request(string strWebSite)
{
List<string> lstWebSites = Program.GetList(strWebSite);
using (var client2 = new TcpClient(strWebSite, 80))
{
using (NetworkStream stream = client2.GetStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader2 = new StreamReader(stream))
{
//writer.AutoFlush = true;
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("HOST: {0}:80", lstWebSites[1]);
writer.WriteLine("Connection: Close");
writer.WriteLine();
writer.WriteLine();
string theresponse = reader2.ReadToEnd();
Console.WriteLine(theresponse);
}
}
}
}
}
IWebRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.IO;
using System.Threading.Tasks;
//using MyWebRequest.Lib;
namespace HTTPrequestApp.MyWebRequest
{
public interface IWebRequest
{
Task<List<strWebSite>> GetList();
void Request();
}
}
To give an over view of what I am trying to accomplish here is: Send HTTP request to get the initial page. Get back the HTTP response and check that it is a 200 response code. And time how long it took to retrieve the response.
This is a console app but I need to not have it depend on the console, it needs to be an independent application so I can use it somewhere else.
If anyone has any suggestions on how I can simplify my code please let me know.
thanks.
You have a HTTPrequestApp.MyWebRequest namespace and a HTTPrequestApp.MyWebRequest class name: c# compiler get confused (and human too...)
Consider renaming the namespace in something such HTTPrequestApp.MyWebRequestNameSpace if you really want a different namespace.

String too small to store standard output of process

I direct the standard output/error of a process and store it in a string which I log to a file.
I have noticed that not all of the standard output is stored in the text file so I must be hitting the size limit of the string.
Does anyone know of an alternative which would help satisfy this issue?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Logging
{
class Logger
{
private FileStream file = null;
private StreamWriter writer = null;
public Logger(string _path)
{
if (!File.Exists(_path)) File.Create(_path).Dispose();
file = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.Write);
writer = new StreamWriter(file);
}
public void Log(string _text)
{
Console.WriteLine(_text);
using (file)
{
writer.WriteLine("[" + DateTime.Now + "] : " + _text);
}
}
}
}
using (file)
You just disposed your file. You can't write to it anymore.
The string type has a limit of 2GB.
Your handling of the file creation and disposal is causing you some difficulty.
Try this for a little cleaner logging code:
const string log = #"logfile path";
public void Log(string _text)
{
try
{
using (TextWriter tw = new StreamWriter(_path, true))
{
tw.WriteLine("[" + DateTime.Now + "] : " + _text);
}
}
catch (Exception)
{
throw;
}
}

How would I write this to a csv file in c#?

I hope someone can help me. I am a beginner at c# and programming in general and I'm trying to complete this program. Basically it looks in an XML file, grabs all of the occurrences of a specific tag and is supposed to write the File Names plus whatever is between any instances of these two tags. So far I've tried TextWriter, StreamWriter, FileStream and some others and nothing doing what I want. I realise this may be a stupid question but I'm a super noob and need help for my particular case. My code is as follows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var files = from file in Directory.GetFiles("W:\\SRC\\hDefMl\\1.0\\Instrument_Files")
orderby file
ascending
select file;
StringBuilder sb_report = new StringBuilder();
string delimiter = ",";
sb_report.AppendLine(string.Join(delimiter, "Module", "Generator(s)"));
foreach (var file in files)
{
string filename = Path.GetFileNameWithoutExtension(file);
Console.WriteLine("The HDefML file for {0} contains these EEPROM Generators:", filename);
XDocument hdefml = XDocument.Load(file);
var GeneratorNames = from b in hdefml.Descendants("Generators")
select new
{
name = (string)b.Element("GeneratorName")
};
string description;
foreach (var generator in GeneratorNames)
{
Console.WriteLine(" GeneratorName is: {0}", generator.name);
sb_report.AppendLine(string.Join(delimiter, filename,
generator.name));
}
}
}
You should be able to just do something like this, if the string you have built with your string builder is formatted correctly.
static void WriteToCSV(string str, string path)
{
using (Stream stream = File.Create(path))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(str);
}
}
try{
FileStream FS;
StreamWriter SW;
using (FS = new FileStream("HardCodedFileName.csv", FileMode.Append))
{
using (SW = new StreamWriter(FS))
{
foreach (var generator in GeneratorNames)
{
SW.WriteLine(string.Join(delimiter, filename,
generator.name));
}
}
}
}
catch (Exception e){
Console.Writeline(e.ToString());
}

Categories

Resources