自己在百度搜索C#开发的企业微信发送图片都写得比较复杂,需要很多信息,种类也比较少;自己写了一个只需要机器人地址和本地图片的小程序,代码如下:
按钮触发
private void button1_Click(object sender, EventArgs e)
{
string b = "机器人地址";
string aaa = string.Empty;
ImageTotextPhoneandUserID(@"E:\11.jpg", out aaa);
PostMessage(aaa, b);
}
图片处理
public bool ImageTotextPhoneandUserID(string filePath, out string strTransferData)
{
string strData = string.Empty;
strTransferData = string.Empty;
bool bTmp = false;
try
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.Append("\"msgtype\":");
sb.Append("\"image\",");
sb.Append("\"image\":");
sb.Append("{");
sb.Append("\"base64\":");
sb.Append("\"");
sb.Append(Convert.ToBase64String(File.ReadAllBytes(filePath)));
sb.Append("\"");
sb.Append(",");
sb.Append("\"md5\":");
sb.Append("\"");
sb.Append(GetMD5HashFromFile(filePath));
sb.Append("\"");
sb.Append("}");
sb.Append("}");//json end symbol
strData = sb.ToString();
bTmp = true;
}
catch (Exception exp)
{
strData = exp.Message;
bTmp = false;
}
strTransferData = strData;
return bTmp;
}
获取图片的MD5
public static string GetMD5HashFromFile(string file)
{
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] retVal = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(fileStream);
fileStream.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
发送企业微信
public bool PostMessage(string Message, string Webhook)
{
try
{
string strReply = string.Empty;
byte[] payload;
// string strGetJsonFormat;
bool btmp = false;
#region Create Web Request
//create web request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Webhook);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
payload = Encoding.UTF8.GetBytes(Message);//transfer string to byte
request.ContentLength = payload.Length;
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
#endregion
#region Get Web Response
//get Response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
string strValue = "";
using (StreamReader reader = new StreamReader(s, Encoding.UTF8))
{
while (!reader.EndOfStream)
{
strValue += reader.ReadLine();
}
}
response.Close();
#endregion
#region reply message check
if (strValue.Split(',')[1].Contains("ok"))
{
strReply = string.Empty;
btmp = true;
}
else
{
strReply = strValue;
btmp = false;
}
#endregion
return btmp;
}
catch (Exception e)
{
return false;
}
}