ECGGather/1200gFtp/commonOptions.cs
2024-12-25 17:21:40 +08:00

637 lines
24 KiB
C#
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace _1200gFtp
{
public class commonOptions
{
/// <summary>
/// 获取福乐云HIS系统的token
/// </summary>
/// <param name="username"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public static string getHisToken(string url1,string appkey, string appsecret)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("appkey", appkey);
dic.Add("appsecret", appsecret);
string resultV = commonOptions.PostFile3(url1, dic);
FlyHisTokenMsgModel tm = JsonConvert.DeserializeObject<FlyHisTokenMsgModel>(resultV);
return tm.data.access_token;
}
/// <summary>
/// 获取福乐云HIS系统的患者基本信息
/// </summary>
/// <param name="username"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public static FlyHisEcgDataModel GetHisEcgData(string url1, string Yiyuanid, string kaifangsj,string token)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("Yiyuanid", Yiyuanid);
dic.Add("kaifangsj", kaifangsj);
dic.Add("token", token);
string resultV = commonOptions.PostFile3(url1, dic);
FlyHisEcgDataModel tm = JsonConvert.DeserializeObject<FlyHisEcgDataModel>(resultV);
return tm;
}
/// <summary>
/// post form-data 参数
/// </summary>
/// <param name="url"></param>
/// <param name="items"></param>
/// <returns></returns>
public static string PostFile3(string url, Dictionary<string, object> items)
{
string boundary = DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = null;
//如果是发送HTTPS请求              
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//处理HttpWebRequest访问https有安全证书的问题 请求被中止: 未能创建 SSL/TLS 安全通道。)
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
// request.Headers.Add("Authorization", "Bearer " + token);
// 最后的结束符
var endBoundary = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
//文件数据
string fileFormdataTemplate =
"--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: application/octet-stream" +
"\r\n\r\n";
//文本数据
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";
//FileInfo fi = new FileInfo(filePath);
//string fileHeader = string.Format(fileFormdataTemplate, "file", fi.Name);
//var fileBytes = Encoding.UTF8.GetBytes(fileHeader);
using (var postStream = new MemoryStream())
{
////写入文件格式串
//postStream.Write(fileBytes, 0, fileBytes.Length);
//#region 写入文件流
//using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
//{
// byte[] buffer = new byte[1024];
// int bytesRead = 0;
// while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
// {
// postStream.Write(buffer, 0, bytesRead);
// }
//}
//#endregion
#region
foreach (KeyValuePair<string, object> key in items)
{
var p = string.Format(dataFormdataTemplate, key.Key, key.Value);
var bp = Encoding.UTF8.GetBytes(p);
postStream.Write(bp, 0, bp.Length);
}
#endregion
//写入结束边界
postStream.Write(endBoundary, 0, endBoundary.Length);
#region
request.ContentLength = postStream.Length;
postStream.Position = 0;
using (Stream ds = request.GetRequestStream())
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
ds.Write(buffer, 0, bytesRead);
}
}
#endregion
#region
string result = string.Empty;
using (HttpWebResponse rep = (HttpWebResponse)request.GetResponse())
{
using (Stream ds = rep.GetResponseStream())
{
using (StreamReader sr = new StreamReader(ds))
{
result = sr.ReadToEnd();
}
}
}
return result;
#endregion
}
}
//public static string PostMoths8(string url, string appkey, string appsecret)
//{
// string strURL = url;
// HttpWebRequest request;
// request = (HttpWebRequest)WebRequest.Create(strURL);
// request.Method = "POST";
// request.ContentType = "application/json;charset=UTF-8";
// string paraUrlCoded = param;
// byte[] payload;
// payload = Encoding.UTF8.GetBytes(paraUrlCoded);
// request.ContentLength = payload.Length;
// Stream writer = request.GetRequestStream();
// writer.Write(payload, 0, payload.Length);
// writer.Close();
// System.Net.HttpWebResponse response;
// response = (System.Net.HttpWebResponse)request.GetResponse();
// System.IO.Stream s;
// s = response.GetResponseStream();
// string StrDate = "";
// string strValue = "";
// StreamReader Reader = new StreamReader(s, Encoding.UTF8);
// while ((StrDate = Reader.ReadLine()) != null)
// {
// strValue += StrDate + "\r\n";
// }
// return strValue;
//}
/// <summary>
/// 获取福乐云的token
/// </summary>
/// <param name="username"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public static string gettoken(string username, string pwd, string url1)
{
loginPara lp = new loginPara();
lp.username = username;
lp.password = commonOptions.Encrypt(pwd);//非对称公钥加密
string loginJson = JsonConvert.SerializeObject(lp);
string resultV = commonOptions.PostMoths(url1, loginJson);
tokenMsg tm = JsonConvert.DeserializeObject<tokenMsg>(resultV);
return tm.data;
}
// 非对称公钥加密 使用公钥加密数据
public static string Encrypt(string plainText)
{
string base64EncryptedData = string.Empty;
// 创建 RSA 密钥对
using (var rsa = new RSACryptoServiceProvider())
{
// 获取公钥
string publicKey = rsa.ToXmlString(false);
// 加载公钥
rsa.FromXmlString("<RSAKeyValue><Modulus>gMIre8vicEqHjwhyrMUSMbwyR+STy9vGDyqmOd9xA4JI9/ghqAQAl5T9R8z87gwKMosPsEaRf4/1tg8taa/q2g0xwcZZ3dZlBzDSQ7k7I7t/Cv+m3YUZDp1U1TooSw8NzX3MQ36u1uiniWAUMvA0PT17dR6dxsQmMdDN4xSJO/0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
// 将待加密数据转换成字节数组
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(plainText);
// 使用公钥加密数据
byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false);
// 将加密后的数据转换为 Base64 编码的字符串
base64EncryptedData = Convert.ToBase64String(encryptedData);
string aaa = "公钥:" + publicKey;
}
return base64EncryptedData;
//byte[] encryptedData = Encoding.UTF8.GetBytes(plainText);
//using (RSA rsa = RSA.Create())
//{
// rsa.ImportParameters(publicKey);
// // return rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
// return Encoding.UTF8.GetString(rsa.Encrypt(encryptedData, RSAEncryptionPadding.Pkcs1));
//}
}
//----------------------------------------------------------------------------------------------------------------------------
// 非对称公钥加密 使用公钥加密数据
public static string Encrypt(string plainText, RSAParameters publicKey)
{
byte[] encryptedData = Encoding.UTF8.GetBytes(plainText);
using (RSA rsa = RSA.Create())
{
rsa.ImportParameters(publicKey);
// return rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
return Encoding.UTF8.GetString(rsa.Encrypt(encryptedData, RSAEncryptionPadding.Pkcs1));
}
}
/// <summary>
/// DES加密
/// </summary>
/// <param name="data">加密数据</param>
/// <param name="key">8位字符的密钥字符串</param>
/// <param name="iv">8位字符的初始化向量字符串</param>
/// <returns></returns>
public static string DESEncrypt(string data, string key, string iv)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="data">解密数据</param>
/// <param name="key">8位字符的密钥字符串(需要和加密时相同)</param>
/// <param name="iv">8位字符的初始化向量字符串(需要和加密时相同)</param>
/// <returns></returns>
public static string DESDecrypt(string data, string key, string iv)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
public static string PostMoths(string url, string param)
{
string strURL = url;
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
string paraUrlCoded = param;
byte[] payload;
payload = Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <param name="token"></param>
/// <param name="jsonContent"></param>
/// <returns></returns>
public static string PostByParas(string url, string token, string jsonContent)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers.Add("Authorization", "Bearer " + token);
byte[] data = Encoding.UTF8.GetBytes(jsonContent);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
/// <summary>
/// 海军给的 http 上传文件 好用版
/// </summary>
/// <param name="url"></param>
/// <param name="filePath"></param>
/// <param name="items"></param>
/// <param name="token"></param>
/// <returns></returns>
public static string PostFile2(string url, string filePath, Dictionary<string, object> items, string token)
{
string boundary = DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = null;
//如果是发送HTTPS请求              
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//处理HttpWebRequest访问https有安全证书的问题 请求被中止: 未能创建 SSL/TLS 安全通道。)
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.Headers.Add("Authorization", "Bearer " + token);
// 最后的结束符
var endBoundary = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
//文件数据
string fileFormdataTemplate =
"--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: application/octet-stream" +
"\r\n\r\n";
//文本数据
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";
FileInfo fi = new FileInfo(filePath);
string fileHeader = string.Format(fileFormdataTemplate, "file", fi.Name);
var fileBytes = Encoding.UTF8.GetBytes(fileHeader);
using (var postStream = new MemoryStream())
{
//写入文件格式串
postStream.Write(fileBytes, 0, fileBytes.Length);
#region
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
}
#endregion
#region
foreach (KeyValuePair<string, object> key in items)
{
var p = string.Format(dataFormdataTemplate, key.Key, key.Value);
var bp = Encoding.UTF8.GetBytes(p);
postStream.Write(bp, 0, bp.Length);
//System.Diagnostics.Debug.WriteLine(p);
}
#endregion
//写入结束边界
postStream.Write(endBoundary, 0, endBoundary.Length);
#region
request.ContentLength = postStream.Length;
postStream.Position = 0;
using (Stream ds = request.GetRequestStream())
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
ds.Write(buffer, 0, bytesRead);
}
}
#endregion
#region
string result = string.Empty;
using (HttpWebResponse rep = (HttpWebResponse)request.GetResponse())
{
using (Stream ds = rep.GetResponseStream())
{
using (StreamReader sr = new StreamReader(ds))
{
result = sr.ReadToEnd();
}
}
}
return result;
#endregion
}
}
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string PostByParas(string url, Dictionary<string, string> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region Post
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
public static string HttpGet(string url)
{
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "text/html, application/xhtml+xml, */*";
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
//public static Image CreateBarCode(string content)
//{
// using (var barcode = new Barcode()
// {
// //true显示contentfalse反之
// IncludeLabel = true,
// //content的位置
// Alignment = AlignmentPositions.CENTER,
// //条形码的宽高
// Width = 145,
// Height = 39,
// //类型
// RotateFlipType = RotateFlipType.RotateNoneFlipNone,
// //颜色
// BackColor = Color.White,
// ForeColor = Color.Black,
// })
// {
// return barcode.Encode(TYPE.CODE128B, content);
// }
//}
/// <summary>
/// 格式化磁盘
/// </summary>
/// <param name="DiskName">盘符名称C:、D:、E:、F:</param>
/// <returns></returns>
public static bool FormatDisk(string DiskName)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
if (process != null)
{
process.StandardInput.WriteLine($"FORMAT {DiskName} /y /FS:FAT32 /V:BMECG /Q");
process.StandardInput.Close();
string outputString = process.StandardOutput.ReadToEnd();
if (outputString.Contains("已完成"))
{
return true;
}
}
return false;
}
//public static void PdfToImages(string pdfFilePath, string outputFolder)
//{
// string imgpath = @"D:/PDFFF/";
// var pathList = GetPdfAllPageImgs(pdfFilePath, imgpath, "11556699");
//}
}
}