C# QRCode, String, File, xml

生成二维码并显示

ref https://jingyan.baidu.com/article/fb48e8bef1ebab6e622e1409.html

1. Visual Studio > 右击项目名 > Manage NuGet Packages... > 搜索Spire.Barcode并安装。当前版本是v3.5.0,VS用的是VS Community 2017 Version 15.9.12

2. Program.cs中Main函数内添加如下代码,生成QR Code:

 1 using Spire.Barcode;
 2 using System.Drawing;
 3 
 4         static void Main(string[] args)
 5         {
 6 
 7             //创建BarcodeSettings对象
 8             BarcodeSettings settings = new BarcodeSettings();         
 9 
10             //设置条码类型为二维码
11             settings.Type = BarCodeType.QRCode;
12 
13             //设置二维码数据
14             settings.Data = "123456789";
15 
16             //设置显示文本
17             settings.Data2D = "123456789";
18 
19             //设置数据类型为数字
20             settings.QRCodeDataMode = QRCodeDataMode.Numeric;
21 
22             //设置二维码错误修正级别
23             settings.QRCodeECL = QRCodeECL.H;
24 
25             //设置宽度
26             settings.X = 3.0f;
27 
28             //实例化BarCodeGenerator类的对象
29             BarCodeGenerator generator = new BarCodeGenerator(settings);
30 
31             //生成二维码图片并保存为PNG格式
32             Image image = generator.GenerateImage();
33             image.Save("QRCode.png"); // not mandatory

3. Form1.cs,将生成的image参数传递给Form以便显示出来

        public Form1(Image image) // add args image
        {
            InitializeComponent(image); // parse image to form

4. Form1.Designer.cs,添加pictureBox用于显示二维码

using System.Drawing; // add name space if report error

        private void InitializeComponent(Image image) // parse image

            this.pictureBox1.Image = image; // show QRCode

            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; // AutoSize根据图片的大小自动扩展pictureBox

 C#字符串

string.Format("https://www.baidu.com/s?wd={0}_{1}", width, height)

 几个经常用到的字符串的截取

string str="123abc456"; int i=3;

  • 取字符串的前i个字符:    str=str.Substring(0,i); // or  str=str.Remove(i,str.Length-i);
  • 去掉字符串的前i个字符:    str=str.Remove(0,i);  // or str=str.Substring(i);
  • 从右边开始取i个字符:   str=str.Substring(str.Length-i); // or str=str.Remove(0,str.Length-i);
  • 从右边开始去掉i个字符:    str=str.Substring(0,str.Length-i); // or str=str.Remove(str.Length-i,i);
  • 判断字符串中是否有"abc" 有则去掉之    using System.Text.RegularExpressions;    string str = "123abc456";    string a="abc";    Regex r = new  Regex(a);    Match m = r.Match(str);    if (m.Success)    {     //绿色部分与紫色部分取一种即可。       str=str.Replace(a,"");       Response.Write(str);         string str1,str2;       str1=str.Substring(0,m.Index);       str2=str.Substring(m.Index+a.Length,str.Length-a.Length-m.Index);       Response.Write(str1+str2);    }
  • 如果字符串中有"abc"则替换成"ABC"    str=str.Replace("abc","ABC");

   ************************************************

  string str="adcdef"; int indexStart = str.IndexOf("d"); int endIndex =str.IndexOf("e"); string toStr = str.SubString(indexStart,endIndex-indexStart); c#截取字符串最后一个字符的问题! str1.Substring(str1.LastIndexOf(",")+1)

 

C#中的File类用法

https://www.cnblogs.com/hmdyc/p/6652839.html

File.Exists(@"路径");//判断文件是否存在,返回一个bool值

File.Move(@"",@"");//剪切

File.Copy(@"",@"");//复制

File.Delete(@"",@"");//彻底删除

File.ReadAllLines(@"");//读取一个文本文件,返回一个字符串数组

string[] str = File.ReadAllLines(@"C:\Users\Administrator\Destop\aa.txt",Encoding.Default); //Encoding.Default使用系统默认编码

for(int i = 0; i < str.Length; i++)

{     Console.WriteLine(str[i]); }

File.ReadAllText(@"");//读取一个文本文件,返回一个字符串

string str = File.ReadAllText(@"C:\Users\Administrator\Destop\aa.txt",Encoding.UTF8);//Encoding.UTF8使用UTF8编码

Console.WriteLine(str);

File.ReadAllBytes(@"");//读取一个文件,返回字节数组

byte[] bt = File.ReadAllBytes(@"C:\Users\Administrator\Destop\aa.txt"); //将byte数组解码成我们认识的字符串

for(int i = 0; i < bt.Length; i++)

{     Console.WriteLine(byte[i].ToString()); }

File.WriteAllLines(@"");//将一串字符串数组写入到一个文本文件,会覆盖源文件。

File.WriteAllText(@"");//将一串字符串写入到一个文本文件中,会覆盖源文件。

File.WriteAllBytes(@"");//将一个字节数组写入到一个文本文件中,会覆盖源文件。

File.AddAllText(@"");//将一个字符串写入到一个文本文件中,不会覆盖源文件。

File.AddAllLines(@"");//……,不覆盖源文件。

File.AddAllBytes(@"");//……,不覆盖源文件。

//将一个任意类型的文件复制到其他位置 byte[] bt = File.ReadAllBytes(@"C:\Users\Administrator\Destop\aa.avi"); File.WriteAllBytes(@"D:\new.avi",bt);

File只能操作小文件,操作大文件速度极慢

C#读写改XML

 1         public static void WriteLogPathToDebugInfo()
 2         {
 3             string debugxml =  Path.GetFullPath("../../") + @"Log\DebugInfo.xml"; // C:\Program Files (x86)\AutoRI\Log\DebugInfo.xml
 4             if (!File.Exists(debugxml)) // XML不存在,创建
 5             {
 6                 Console.WriteLine(string.Format("Not find {0}, create it", debugxml));
 7                 XmlDocument xmlDoc = new XmlDocument(); // 创建XmlDocument对象
 8                 XmlDeclaration xmlSM = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); // XML的声明<?xml version="1.0" encoding="utf-8"?> 
 9                 xmlDoc.AppendChild(xmlSM); // 追加xmldecl位置
10                 XmlElement xml = xmlDoc.CreateElement("", "debuginfo", ""); // 添加一个名为debuginfo的根节点
11                 xmlDoc.AppendChild(xml); // 追加debuginfo的根节点位置
12                 XmlNode gen = xmlDoc.SelectSingleNode("debuginfo"); // 添加另一个节点,与debuginfo所匹配,查找<debuginfo>
13                 XmlElement zi = xmlDoc.CreateElement("name"); //添加一个名为<name>的节点   
14                 zi.SetAttribute("type", "BurnIn Test"); //<name>节点的属性
15                 XmlElement x1 = xmlDoc.CreateElement("logpath");
16                 x1.InnerText = Path.GetFullPath("../../") + @"Log\BurnInTest.log"; //InnerText:获取或设置节点及其所有子节点的串连值
17                 zi.AppendChild(x1); //添加到<Zi>节点中
18                 gen.AppendChild(zi);//添加到<Gen>节点中   
19                 xmlDoc.Save(debugxml);//"debuginfo.xml");
20             }
21             else // XML已经存在,如查找到则修改并置flag
22             {
23                 bool findnode = false;
24                 XmlDocument xmlDoc = new XmlDocument();
25                 xmlDoc.Load(debugxml);
26 
27                 XmlNodeList nodeList = xmlDoc.SelectSingleNode("debuginfo").ChildNodes;//获取Employees节点的所有子节点
28                 foreach (XmlNode xn in nodeList)//遍历所有子节点 
29                 {
30                     XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型 
31                     if (xe.GetAttribute("type") == "BurnIn Test")//如果type属性值为“BurnIn Test” 
32                     {
33                         //xe.SetAttribute("type", "3D Mark11_M");//则修改该属性为“update张三”
34                         XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点 
35                         foreach (XmlNode xn1 in nls)//遍历 
36                         {
37                             XmlElement xe2 = (XmlElement)xn1;//转换类型 
38                             if (xe2.Name == "logpath")//如果找到 
39                             {
40                                 xe2.InnerText = Path.GetFullPath("../../") + @"Log\BurnInTest.log";//则修改
41                                 Console.WriteLine("Find " + debugxml + @" and BurnIn Test node, write its logpath to C:\BurnIn_Logs\BIT.log");
42                                 findnode = true; 
43                             }
44                         }
45                     }
46                 }
47                 if (findnode == false) // 找不到此Node,添加
48                 {
49                     Console.WriteLine("Find " + debugxml + " But NOT find BurnIn Test node, create it and append logpath");
50                     XmlNode root = xmlDoc.SelectSingleNode("debuginfo"); // 查找 
51                     XmlElement xe1 = xmlDoc.CreateElement("name"); // 创建一个节点 
52                     xe1.SetAttribute("type", "BurnIn Test"); // 设置该节点genre属性 
53                     XmlElement xesub1 = xmlDoc.CreateElement("logpath");
54                     xesub1.InnerText = Path.GetFullPath("../../") + @"Log\BurnInTest.log"; // 设置文本节点 
55                     xe1.AppendChild(xesub1); // 添加到节点中 
56                     root.AppendChild(xe1); // 添加到节点中 
57                 }
58                 xmlDoc.Save(debugxml); // 保存。
59             }
60         }

 

C#获取ini文件中全部Section,获取Section下全部Key

 

using System.Runtime.InteropServices;
[DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
private static extern uint GetPrivateProfileStringA(string section, string key, string def, Byte[] retVal, int size, string filePath);

static void Main(string[] args)
{
    string[] sections = ReadSections(@"C:\Users\yinguo.li.LCFC\Desktop\aa\aa\bin\Debug\Modules.ini").ToArray();
    string[] keys = ReadKeys("Thermal_TAT", @"C:\Users\yinguo.li.LCFC\Desktop\aa\aa\bin\Debug\Modules.ini").ToArray();
    foreach (string section in sections)
        Console.WriteLine(section);
    foreach (string key in keys)
        Console.WriteLine(key);
}

public static List ReadSections(string iniFilename)
{
    List result = new List();
    Byte[] buf = new Byte[65536];
    uint len = GetPrivateProfileStringA(null, null, null, buf, buf.Length, iniFilename);
    int j = 0;
    for (int i = 0; i < len; i++)
        if (buf[i] == 0)
        {
            result.Add(Encoding.Default.GetString(buf, j, i - j));
            j = i + 1;
        }
    return result;
}

public static List ReadKeys(string SectionName, string iniFilename)
{
    List result = new List();
    Byte[] buf = new Byte[65536];
    uint len = GetPrivateProfileStringA(SectionName, null, null, buf, buf.Length, iniFilename);
    int j = 0;
    for (int i = 0; i < len; i++)
        if (buf[i] == 0)
        {
            result.Add(Encoding.Default.GetString(buf, j, i - j));
            j = i + 1;
        }
    return result;
}

转载于:https://www.cnblogs.com/yinguo/p/11103797.html

using System; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using DouYinPush.Model; using DouYinPush.Model.DouYinVideo.New; using Fandi.Common.Convert; using Fandi.Common.Helper; using Newtonsoft.Json; namespace DouYinPush.Helper; public class RequestOperate { private static T HttpGet<T>(string url, string cookie) { T val = default(T); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; using WebClient webClient = new WebClient(); webClient.Headers.Add("Referer", "https://www.douyin.com/"); webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"); webClient.Headers.Add("Cookie", cookie); byte[] bytes = webClient.DownloadData(url); string value = Encoding.UTF8.GetString(bytes); return JsonConvert.DeserializeObject<T>(value); } catch (Exception) { throw; } } private static T HttpPost<T>(string url, string param, string cookie) { T result = default(T); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; using WebClient webClient = new WebClient(); byte[] bytes = Encoding.UTF8.GetBytes(param); webClient.Headers.Add("Cookie", cookie); byte[] bytes2 = webClient.UploadData(url, "POST", bytes); string value = Encoding.UTF8.GetString(bytes2); result = JsonConvert.DeserializeObject<T>(value); return result; } catch (Exception ex) { if (!url.StartsWith("https://webcast.amemv.com/webcast/room/ping/anchor/")) { LogHelper.WriteException(ex, "HttpPost"); } } return result; } public static GetQrCodeResponse GetQrCodeInfo() { return HttpGet<GetQrCodeResponse>("https://sso.douyin.com/get_qrcode/?service=https%3A%2F%2Fwebcast.amemv.com&need_logo=false&aid=10006&account_sdk_source=sso&language=zh", ""); } public static string GetHtml(string url) { string result = ""; try { WebRequest webRequest = WebRequest.Create(url); webRequest.Method = "GET"; webRequest.Headers.Add("Cookie", CacheHelper.look_video_cookie); WebResponse response = webRequest.GetResponse(); Stream responseStream = response.GetResponseStream(); Encoding encoding = Encoding.Default; StreamReader streamReader = new StreamReader(responseStream, encoding); result = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); response.Close(); } catch (Exception) { } return result; } public static QueryScanQrCodeStatusResponse GetQrCodeStatus() { return HttpGet<QueryScanQrCodeStatusResponse>("https://sso.douyin.com/check_qrconnect/?service=https%3A%2F%2Fwebcast.amemv.com&token=" + CacheHelper.token + "&need_logo=false&is_frontier=false&aid=10006&account_sdk_source=sso&language=zh", ""); } public static StreamUrlResponse GetPushUrl() { return HttpPost<StreamUrlResponse>("https://webcast.amemv.com/webcast/room/get_latest_room/?ac=wifi&app_name=webcast_mate&version_code=2.2.9&device_platform=windows&webcast_sdk_version=1520&resolution=1920%2A1080&os_version=10.0.19043&language=zh&aid=2079&live_id=1&channel=online&device_id=3096676051989080&iid=1117559680415880", "", CacheHelper.cookie); } public static void PingAnchor() { if (!CacheHelper.room_id.IsEmpty() && !CacheHelper.stream_id.IsEmpty()) { HttpPost<RoomPingResponse>("https://webcast.amemv.com/webcast/room/ping/anchor/?ac=wifi&app_name=webcast_mate&version_code=2.2.9&device_platform=windows&webcast_sdk_version=1520&resolution=1920%2A1080&os_version=10.0.19043&language=zh&aid=2079&live_id=1&channel=online&device_id=3096676051989080&iid=1117559680415880", "stream_id=" + CacheHelper.stream_id + "&room_id=" + CacheHelper.room_id + "&status=2", CacheHelper.cookie); } } public static LiveInfoItemEntity GetLiveInfoByID(string web_r_id) { return HttpGet<LiveInfoItemEntity>("https://live.douyin.com/webcast/room/web/enter/?aid=6383&app_name=douyin_web&live_id=1&device_platform=web&language=zh-CN&enter_from=page_refresh&cookie_enabled=true&screen_width=1920&screen_height=1080&browser_language=zh-CN&browser_platform=Win32&browser_name=Edge&browser_version=127.0.0.0&web_rid=" + web_r_id + "&enter_source=&is_need_double_stream=false&insert_task_id=&live_reason=", CacheHelper.cookie); } public static void CloseLive() { if (!CacheHelper.stream_id.IsEmpty() && !CacheHelper.room_id.IsEmpty() && !CacheHelper.cookie.IsEmpty()) { RoomPingResponse roomPingResponse = HttpPost<RoomPingResponse>("https://webcast.amemv.com/webcast/room/ping/anchor/?ac=wifi&app_name=webcast_mate&version_code=8.6.1&device_platform=windows&webcast_sdk_version=1520&resolution=1920%2A1080&os_version=10.0.19045&language=zh&aid=2079&live_id=1&channel=online&device_id=4229146318764409&iid=2566679780145658&msToken=Q6DSpfUwpMfquGjBJTh2oplGdt2OqLSidNY-HegSpQysL8_lZgft_GgLedjiJvtseHO0AU8sU4cJT5woBO8hG4Kt8cR5NvW5l0GjqSsJJK4-gxLL0w==&X-Bogus=DFSzswVuZFVuRe0FtQCB6rl849N7&_signature=_02B4Z6wo00001uxlUIwAAIDBRSaf3TbcWzbsZVQAANwPrarTWR064S2XsK2HpvtNj1lRBCGX5VsHWhCGawcNNtUheDXzOgM4dCF3J3bOFDSX8cIdchJRQDmHOpFyiLhZ3ReEUoH4Vow.QTj54c", "stream_id=" + CacheHelper.stream_id + "&room_id=" + CacheHelper.room_id + "&status=4", CacheHelper.cookie); if (roomPingResponse.status_code == 0) { MessageHelper.WarningMsg("直播已关闭!"); return; } MessageHelper.WarningMsg(roomPingResponse.data.prompts + "(" + roomPingResponse.data.message + "-" + roomPingResponse.status_code + ")"); } else { MessageHelper.WarningMsg("未检测到开播信息!"); } } public static string RequestUrl(string url) { return GetRedirectUrl(url); } public static string GetRedirectUrl(string url, int type = 0, string cookies = "") { string result = ""; try { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "HEAD"; httpWebRequest.AllowAutoRedirect = false; string userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2"; if (type > 0) { userAgent = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; } httpWebRequest.UserAgent = userAgent; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; if (!cookies.IsEmpty()) { httpWebRequest.Headers.Add("Cookie", cookies); } using WebResponse webResponse = httpWebRequest.GetResponse(); result = webResponse.Headers["Location"]; } catch (Exception) { throw new Exception("地址重定向错误!"); } return result; } public static bool DownMP4(string url, string savePath) { bool result = false; try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Referer = url; WebResponse response = httpWebRequest.GetResponse(); if (response.ContentType.ToLower().Length > 0) { using (Stream stream = response.GetResponseStream()) { using FileStream fileStream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write); byte[] array = new byte[1024]; int num = 0; while ((num = stream.Read(array, 0, array.Length)) > 0) { fileStream.Write(array, 0, num); } } result = true; } } catch (Exception ex) { LogHelper.WriteException(ex); } return result; } public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } }
最新发布
08-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值