Communicate with Bitcoin-qt using C# / .NET

Code used in video

private static void Main(string[] args)
{
var data = RequestServer(“getblockcount”, new List<string>() { “value”});
Console.WriteLine(data);
Console.ReadKey();
}

public static string RequestServer(string methodName, List<string> parameters)
{

string ServerIp = “http://localhost.:8332”;
string UserName = “BtcMyFineUserForTesting”;
string Password = “sdfaf5143gEAD”;

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ServerIp);
webRequest.Credentials = new NetworkCredential(UserName, Password);

webRequest.ContentType = “application/json-rpc”;
webRequest.Method = “POST”;

string respVal = string.Empty;

JObject joe = new JObject();
joe.Add(new JProperty(“jsonrpc”, “1.0”));
joe.Add(new JProperty(“id”, “1”));
joe.Add(new JProperty(“method”, methodName));

JArray props = new JArray();
foreach (var parameter in parameters)
{
props.Add(parameter);
}

joe.Add(new JProperty(“params”, props));

// serialize json for the request
string s = JsonConvert.SerializeObject(joe);
byte[] byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

StreamReader streamReader = null;
try
{
WebResponse webResponse = webRequest.GetResponse();

streamReader = new StreamReader(webResponse.GetResponseStream(), true);

respVal = streamReader.ReadToEnd();
var data = JsonConvert.DeserializeObject(respVal).ToString();
return data;
}
catch (Exception exp)
{

}
finally
{
if (streamReader != null)
{
streamReader.Close();
}

}
return string.Empty;
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *