C# 企业微信发送本地图片

自己在百度搜索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;
            }
        }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中使用企业微信 API 可以通过发送 HTTP 请求来与企业微信进行交互。你可以使用 HttpClient 类来发送请求,并通过调用企业微信 API 的不同接口来实现各种功能,如发送消息、获取用户信息等。 首先,你需要在企业微信后台注册一个应用,并获取到应用的相关信息,包括企业ID、应用ID、应用密钥等。 下面是一个示例代码,演示如何使用 C# 发送消息到企业微信: ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { string corpId = "your-corp-id"; string appSecret = "your-app-secret"; string agentId = "your-agent-id"; string accessToken = await GetAccessToken(corpId, appSecret); if (!string.IsNullOrEmpty(accessToken)) { await SendMessage(accessToken, agentId, "user-id", "Hello from C#!"); } } static async Task<string> GetAccessToken(string corpId, string appSecret) { using (HttpClient client = new HttpClient()) { string url = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={appSecret}"; HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); // 解析响应获取 access_token // 注意:实际开发中,建议将 access_token 缓存在本地,并定期更新 // 这里仅为示例,直接返回获取到的 access_token return "your-access-token"; } else { Console.WriteLine($"Failed to get access token. Status code: {response.StatusCode}"); return null; } } } static async Task SendMessage(string accessToken, string agentId, string userId, string message) { using (HttpClient client = new HttpClient()) { string url = $"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={accessToken}"; string requestBody = $"{{\"touser\": \"{userId}\", \"agentid\": \"{agentId}\", \"msgtype\": \"text\", \"text\": {{\"content\": \"{message}\"}}}}"; StringContent content = new StringContent(requestBody, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(url, content); if (response.IsSuccessStatusCode) { Console.WriteLine("Message sent successfully."); } else { Console.WriteLine($"Failed to send message. Status code: {response.StatusCode}"); } } } } ``` 请替换代码中的 `your-corp-id`、`your-app-secret`、`your-agent-id` 和 `user-id` 分别为你的企业ID、应用密钥、应用ID和发送消息的用户ID。这个示例代码是使用企业微信的消息推送接口发送文本消息给指定用户。 希望这个示例能帮到你,如果有其他问题,请随时提问!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值