C# 笔记

目录

1.string转流

2.RSA个人笔记类(XML+PEM格式)【十分杂乱】

3.RSA简单操作类(XML+PEM)【来源个人笔记类整理结果】

4.从资源文件中拉取(获取/下载)文件

5.获取串口名称

6.WriteINI

7.反射与泛型_DataTable 转 类   的操作类

8.随缘更新0.0     。。。。。。。。。。


1.string转流

string str= "123";
StringReader sr = new StringReader(str);

2.RSA个人笔记类(XML+PEM格式)【十分杂乱】

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace RSA加解密
{
    public class RSA
    {
        #region RSA 的密钥产生
        /// <summary>
        /// 生成密钥对【XML格式】
        /// </summary>
        /// <param name="xmlKeys">私钥</param>
        /// <param name="xmlPublicKey">公钥</param>
        public static void XMLRSAKey(out string xmlKeys, out string xmlPublicKey)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                xmlKeys = rsa.ToXmlString(true);
                xmlPublicKey = rsa.ToXmlString(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 生成密钥对【Pem格式】
        /// </summary>
        /// <param name="pemKeys"></param>
        /// <param name="pemPublicKey"></param>
        public static void PemRSAKey(out string pemKeys, out string pemPublicKey)
        {
            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                pemKeys = XmlToPemPrivate(rsa.ToXmlString(true));
                pemPublicKey = XmlToPemPublic(rsa.ToXmlString(false));
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region RSA加密函数
        //############################################################################## 
        //RSA 方式加密 
        //KEY必须是XML的形式,返回的是字符串 
        //该加密方式有长度限制的!
        //############################################################################## 

        /// <summary>
        /// RSA加密【XML格式,字符串】
        /// </summary>
        /// <param name="xmlPublicKey">公钥</param>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns></returns>
        public static string XMLRSAEncrypt(string xmlPublicKey, string encryptString)
        {
            try
            {
                byte[] PlainTextBArray;
                byte[] CypherTextBArray;
                string Result;
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPublicKey);
                PlainTextBArray = (new UnicodeEncoding()).GetBytes(encryptString);
                CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
                Result = Convert.ToBase64String(CypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        /// <summary>
        /// RSA加密【XML格式,字节】
        /// </summary>
        /// <param name="xmlPublicKey">公钥</param>
        /// <param name="EncryptString">待加密的字节数组</param>
        /// <returns></returns>
        public string XMLRSAEncrypt(string xmlPublicKey, byte[] EncryptString)
        {
            try
            {
                byte[] CypherTextBArray;
                string Result;
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPublicKey);
                CypherTextBArray = rsa.Encrypt(EncryptString, false);
                Result = Convert.ToBase64String(CypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA加密【Pem格式】
        /// </summary>
        /// <param name="PubKey">公钥</param>
        /// <param name="data">需加密数据</param>
        /// <returns></returns>
        public static string PemRSAEncrypt(string PubKey, string data)
        {
            StringReader sr = new StringReader(PubKey);
            AsymmetricKeyParameter publickey = new PemReader(sr).ReadObject() as AsymmetricKeyParameter;

            if (publickey == null)
                throw new Exception("私钥读取失败");

            try
            {
                var engine = new Pkcs1Encoding(new RsaEngine());
                engine.Init(true, publickey);


                byte[] bytes = Encoding.UTF8.GetBytes(data);//Encoding.UTF8.GetBytes(data);
                bytes = engine.ProcessBlock(bytes, 0, bytes.Length);

                return Convert.ToBase64String(bytes);// Convert.ToBase64String(bytes);
            }
            catch
            {
                throw new Exception("加密失败");
            }
        }

        #endregion

        #region RSA的解密函数        
        /// <summary>
        /// RSA解密【XML格式,字符串】
        /// </summary>
        /// <param name="xmlPrivateKey">私钥</param>
        /// <param name="decryptString">待解密的字符串</param>
        /// <returns></returns>
        public static string XMLRSADecrypt(string xmlPrivateKey, string decryptString)
        {
            try
            {
                byte[] PlainTextBArray;
                byte[] DypherTextBArray;
                string Result;
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                PlainTextBArray = Convert.FromBase64String(decryptString);
                DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// RSA解密【XML格式,字节】 
        /// </summary>
        /// <param name="xmlPrivateKey">私钥</param>
        /// <param name="DecryptString">待解密的字节数组</param>
        /// <returns></returns>
        public string XMLRSADecrypt(string xmlPrivateKey, byte[] DecryptString)
        {
            try
            {
                byte[] DypherTextBArray;
                string Result;
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(xmlPrivateKey);
                DypherTextBArray = rsa.Decrypt(DecryptString, false);
                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
                return Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// RSA解密【Pem格式,字符串】
        /// </summary>
        /// <param name="PriKey">私钥</param>
        /// <param name="str">加密字后符串</param>
        /// <returns></returns>
        public static string PemRSADecrypt(string PriKey, string str)
        {
            byte[] bytes = Convert.FromBase64String(str);// Convert.FromBase64String(data);
            StringReader sr = new StringReader(PriKey);
            AsymmetricKeyParameter prikey = new PemReader(sr).ReadObject() as AsymmetricKeyParameter;

            if (prikey == null)
                throw new Exception("私钥读取失败");

            try
            {
                var engine = new Pkcs1Encoding(new RsaEngine());
                engine.Init(false, prikey);
                bytes = engine.ProcessBlock(bytes, 0, bytes.Length);

                return Encoding.UTF8.GetString(bytes);Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                throw new Exception("解密失败");
            }
        }

        #endregion

        #region 签名

        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="str">需签名的数据</param>
        /// <returns>签名后的值</returns>
        public static string XMLSign(string str, string str_privateKey)
        {
            //根据需要加签时的哈希算法转化成对应的hash字符节
            byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str);
            var sha256 = new SHA256CryptoServiceProvider();
            byte[] rgbHash = sha256.ComputeHash(bt);

            RSACryptoServiceProvider key = new RSACryptoServiceProvider();
            key.FromXmlString(str_privateKey);
            RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
            formatter.SetHashAlgorithm("SHA256");                                            //此处是你需要加签的hash算法,需要和上边你计算的hash值的算法一致,不然会报错。
            byte[] inArray = formatter.CreateSignature(rgbHash);
            return Convert.ToBase64String(inArray);
        }

        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="str">需签名的数据</param>
        /// <returns>签名后的值</returns>
        public static string PemSign(string str, string str_privateKey)
        {
            str_privateKey = PemToXmlKey(str_privateKey, true);
            //根据需要加签时的哈希算法转化成对应的hash字符节
            byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str);
            var sha256 = new SHA256CryptoServiceProvider();
            byte[] rgbHash = sha256.ComputeHash(bt);

            RSACryptoServiceProvider key = new RSACryptoServiceProvider();
            key.FromXmlString(str_privateKey);
            RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
            formatter.SetHashAlgorithm("SHA256");                                            //此处是你需要加签的hash算法,需要和上边你计算的hash值的算法一致,不然会报错。
            byte[] inArray = formatter.CreateSignature(rgbHash);
            return Convert.ToBase64String(inArray);
        }

        /// <summary>
        /// 签名验证
        /// </summary>
        /// <param name="str">待验证的字符串</param>
        /// <param name="sign">加签之后的字符串</param>
        /// <returns>签名是否符合</returns>
        public static bool XMLSignCheck(string str, string sign, string str_publicKey)
        {
            try
            {
                byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str);
                var sha256 = new SHA256CryptoServiceProvider();
                byte[] rgbHash = sha256.ComputeHash(bt);

                RSACryptoServiceProvider key = new RSACryptoServiceProvider();
                key.FromXmlString(str_publicKey);
                RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
                deformatter.SetHashAlgorithm("SHA256");
                byte[] rgbSignature = Convert.FromBase64String(sign);
                if (deformatter.VerifySignature(rgbHash, rgbSignature))
                {
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 签名验证
        /// </summary>
        /// <param name="str">待验证的字符串</param>
        /// <param name="sign">加签之后的字符串</param>
        /// <returns>签名是否符合</returns>
        public static bool PemSignCheck(string str, string sign, string str_publicKey)
        {
            try
            {
                str_publicKey = PemToXmlKey(str_publicKey, false);
                byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str);
                var sha256 = new SHA256CryptoServiceProvider();
                byte[] rgbHash = sha256.ComputeHash(bt);

                RSACryptoServiceProvider key = new RSACryptoServiceProvider();
                key.FromXmlString(str_publicKey);
                RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
                deformatter.SetHashAlgorithm("SHA256");
                byte[] rgbSignature = Convert.FromBase64String(sign);
                if (deformatter.VerifySignature(rgbHash, rgbSignature))
                {
                    return true;
                }
                return false;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        #endregion

        #region xml转pem

        //参考连接:https://www.jianshu.com/p/faefcc58c79b
        //工具网址1:https://the-x.cn/certificate/PemToXml.aspx
        //工具网址2:https://superdry.apphb.com/tools/online-rsa-key-converter
        //需要依赖一个第三方库,叫BouncyCastle ;在线获取安装包的代码是:PM >Install-Package BouncyCastle


        /// <summary>
        ///  XML格式公钥转PEM格式公钥
        /// </summary>
        /// <param name="xml">XML格式的公钥</param>
        /// <param name="saveFile">保存文件的物理路径</param>
        public static string XmlToPemPublic(string xml, string saveFile = "")
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xml);
            var p = rsa.ExportParameters(false);
            RsaKeyParameters key = new RsaKeyParameters(false, new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent));
            //从Pem文件读取
            //using (var sw = new StreamWriter(saveFile))
            //{
            //    var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
            //    pemWriter.WriteObject(key);
            //}

            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            string publicKey = Convert.ToBase64String(serializedPublicBytes);
            return Format(publicKey, 1);
        }

        /// <summary>
        ///  XML格式私钥转PEM
        /// </summary>
        /// <param name="xml">XML格式私钥</param>
        /// <param name="saveFile">保存文件的物理路径</param>
        public static string XmlToPemPrivate(string xml, string saveFile = "")
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xml);
            var p = rsa.ExportParameters(true);
            var key = new RsaPrivateCrtKeyParameters(
                new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D),
                new BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ),
                new BigInteger(1, p.InverseQ));
            //从Pem文件读取
            //using (var sw = new StreamWriter(saveFile))
            //{
            //    var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
            //    pemWriter.WriteObject(key);
            //}

            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);
            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            string privateKey = Convert.ToBase64String(serializedPrivateBytes);
            return Format(privateKey, 2);
        }

        /// <summary>
        ///  格式化公钥/私钥
        /// </summary>
        /// <param name="key">生成的公钥/私钥</param>
        /// <param name="type">1:公钥 2:私钥</param>
        /// <returns>PEM格式的公钥/私钥</returns>
        public static string Format(string key, int type)
        {
            string result = string.Empty;

            int length = key.Length / 64;
            for (int i = 0; i < length; i++)
            {
                int start = i * 64;
                result = result + key.Substring(start, 64) + "\r\n";
            }

            result = result + key.Substring(length * 64);
            if (type == 1)
            {
                result = result.Insert(0, "-----BEGIN PUBLIC KEY-----\r\n");
                result += "\r\n-----END PUBLIC KEY-----";
            }
            if (type == 2)
            {
                result = result.Insert(0, "-----BEGIN PRIVATE KEY-----\r\n");
                result += "\r\n-----END PRIVATE KEY-----";
            }

            return result;
        }



        /// <summary>
        /// XML密钥转Pem密钥
        /// </summary>
        /// <param name="RSAKey">RSA密钥</param>
        /// <param name="isPrivateKey">是否是私钥</param>
        /// <returns>Pem密钥</returns>
        public static string XmlKeyToPem(string RSAKey, bool isPrivateKey)
        {
            string pemKey = string.Empty;
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(RSAKey);
            RSAParameters rsaPara = new RSAParameters();
            RsaKeyParameters key = null;
            //RSA私钥
            if (isPrivateKey)
            {
                rsaPara = rsa.ExportParameters(true);
                key = new RsaPrivateCrtKeyParameters(
                    new BigInteger(1, rsaPara.Modulus), new BigInteger(1, rsaPara.Exponent), new BigInteger(1, rsaPara.D),
                    new BigInteger(1, rsaPara.P), new BigInteger(1, rsaPara.Q), new BigInteger(1, rsaPara.DP), new BigInteger(1, rsaPara.DQ),
                    new BigInteger(1, rsaPara.InverseQ));
            }
            //RSA公钥
            else
            {
                rsaPara = rsa.ExportParameters(false);
                key = new RsaKeyParameters(false,
                    new BigInteger(1, rsaPara.Modulus),
                    new BigInteger(1, rsaPara.Exponent));
            }
            using (TextWriter sw = new StringWriter())
            {
                var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                pemWriter.WriteObject(key);
                pemWriter.Writer.Flush();
                pemKey = sw.ToString();
            }
            return pemKey;
        }

        #endregion

        #region Pem转xml

        /// <summary>
        ///  一对Pem格式密钥转xml
        /// </summary>
        /// <param name="PrivateKey"></param>
        /// <param name="PublicKey"></param>
        /// <param name="XmlPriKey"></param>
        /// <param name="XmlPubKey"></param>
        public static void CouplePemToXml(string PrivateKey, string PublicKey, out string XmlPriKey, out string XmlPubKey)
        {
            PrivateKey = PrivateKey.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "");
            PublicKey = PublicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "");
            //-------------------------------------------将PEM格式密钥对转换为XML格式密钥对------------------------------------------

            //将PEM格式的密钥对转换为XML格式供以下加密解密使用

            //PEM格式私钥转XML格式
            RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(PrivateKey));
            RSACryptoServiceProvider rcsp = new RSACryptoServiceProvider();
            RSAParameters parms = new RSAParameters();
            //So the thing changed is offcourse the ToByteArrayUnsigned() instead of
            //ToByteArray()
            //将私钥的因子、参数等信息序列化进RSAParameters对象中,私钥中的Modulus和Exponent按照某种规则组合起来其实就是公钥!
            parms.Modulus = privateKey.Modulus.ToByteArrayUnsigned();
            parms.P = privateKey.P.ToByteArrayUnsigned();
            parms.Q = privateKey.Q.ToByteArrayUnsigned();
            parms.DP = privateKey.DP.ToByteArrayUnsigned();
            parms.DQ = privateKey.DQ.ToByteArrayUnsigned();
            parms.InverseQ = privateKey.QInv.ToByteArrayUnsigned();
            parms.D = privateKey.Exponent.ToByteArrayUnsigned();
            parms.Exponent = privateKey.PublicExponent.ToByteArrayUnsigned();
            //So now this now appears to work.
            rcsp.ImportParameters(parms);
            PrivateKey = rcsp.ToXmlString(true);//XML秘钥
                                                //PEM格式公钥转XML格式
                                                //公钥的转换只需要提供Modulus(译:模数、系数)和Exponent(译:指数)两个参数即可,以下代码为只转换公钥。
                                                //------------------------------------------------------------------------------------------------------------------------
                                                //RsaKeyParameters publicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(PublicKey));
                                                //parms = new RSAParameters();
                                                //rcsp = new RSACryptoServiceProvider();
                                                //parms.Modulus = publicKey.Modulus.ToByteArrayUnsigned();
                                                //parms.Exponent = publicKey.Exponent.ToByteArrayUnsigned();
                                                //rcsp.ImportParameters(parms);
                                                //------------------------------------------------------------------------------------------------------------------------
            PublicKey = rcsp.ToXmlString(false);//XML公钥
            XmlPriKey = PrivateKey;
            XmlPubKey = PublicKey;
        }

        /// <summary>
        /// Pem密钥转XML密钥
        /// </summary>
        /// <param name="pemKey">Pem密钥</param>
        /// <param name="isPrivateKey">是否是私钥</param>
        /// <returns>RSA密钥</returns>
        public static string PemToXmlKey(string pemKey, bool isPrivateKey)
        {
            if (isPrivateKey)
            {
                pemKey = pemKey.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "");
            }
            else
            {
                pemKey = pemKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "");
            }
            string rsaKey = string.Empty;
            object pemObject = null;
            RSAParameters rsaPara = new RSAParameters();
            using (StringReader sReader = new StringReader(pemKey))
            {
                var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sReader);
                pemObject = pemReader.ReadObject();
            }
            //RSA私钥
            if (isPrivateKey)
            {
                RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(pemKey));
                rsaPara = new RSAParameters
                {
                    Modulus = key.Modulus.ToByteArrayUnsigned(),
                    Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                    D = key.Exponent.ToByteArrayUnsigned(),
                    P = key.P.ToByteArrayUnsigned(),
                    Q = key.Q.ToByteArrayUnsigned(),
                    DP = key.DP.ToByteArrayUnsigned(),
                    DQ = key.DQ.ToByteArrayUnsigned(),
                    InverseQ = key.QInv.ToByteArrayUnsigned(),
                };
            }
            //RSA公钥
            else
            {
                RsaKeyParameters key = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(pemKey));
                rsaPara.Modulus = key.Modulus.ToByteArrayUnsigned();
                rsaPara.Exponent = key.Exponent.ToByteArrayUnsigned();
            }
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(rsaPara);
            using (StringWriter sw = new StringWriter())
            {
                sw.Write(rsa.ToXmlString(isPrivateKey ? true : false));
                rsaKey = sw.ToString();
            }
            return rsaKey;
        }

        #endregion

    }
}

3.RSA简单操作类(XML+PEM)【来源个人笔记类整理结果】

点击进入查看----->      C# RSA操作类(XML与PEM互转)带demo

4.从资源文件中拉取(获取/下载)文件

可以把文件放在exe内,而不是很多资源文件夹

首先需要把文件放入资源文件夹

然后将资源文件改为嵌入式资源

然后就开始码代码啦!

 

/// <summary>
        /// 从资源文件中抽取资源文件
        /// </summary>
        /// <param name="resFileName">资源文件名称(资源文件名称必须包含目录,目录间用“.”隔开,最外层是项目默认命名空间)</param>
        /// <param name="outputFile">输出文件</param>
        public static void ExtractResFile(string resFileName, string outputFile)
        {
            BufferedStream inStream = null;
            FileStream outStream = null;
            try
            {
                Assembly asm = Assembly.GetExecutingAssembly(); //读取嵌入式资源
                inStream = new BufferedStream(asm.GetManifestResourceStream(resFileName));
                outStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);

                byte[] buffer = new byte[1024];
                int length;

                while ((length = inStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    outStream.Write(buffer, 0, length);
                }
                outStream.Flush();
            }
            finally
            {
                if (outStream != null)
                {
                    outStream.Close();
                }
                if (inStream != null)
                {
                    inStream.Close();
                }
            }
        }




//调用示例:
//ExtractResFile("命名空间.Resources.CSSReadCardNoServices.exe", @"C:\Program Files (x86)\CSSReadCardNo\CSSReadCardNoServices.exe");



5.获取串口名称

//需要再引用中添加该命名空间
using System.Management;


private static void GetMyComName()
        {
            try
            {
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity"))
                {
                    var hardInfos = searcher.Get();
                    int index = 1;
                    foreach (var hardInfo in hardInfos)
                    {
                        if (hardInfo.Properties["Name"].Value != null && hardInfo.Properties["Name"].Value.ToString().Contains("(COM"))
                        {
                            String strComName = hardInfo.Properties["Name"].Value.ToString();//这是获取到的串口名称
//以下是截取需要的串口名称,从而获得串口号,comname是定义的全局变量,大家可以适当修改即可
                            if (strComName.Contains("USB Serial Port"))
                            {
                                comname = System.Text.RegularExpressions.Regex.Replace(strComName, @"(.*\()(.*)(\).*)", "$2");
                                return;
                            }
                            else
                            {
                                comname = "";
                            }
                            index += 1;
                        }
                    }
                }
                Console.ReadKey();
            }
            catch
            {

            }
        }

6.WriteINI

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CSInOutRegistration
{
    public class WriteINI
    {
        public static string inipath = AppDomain.CurrentDomain.BaseDirectory + "Config.ini";

        //声明API函数

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        /// <summary> 
        /// 构造方法 
        /// </summary> 
        /// <param name="INIPath">文件路径</param> 
        public void IniFiles(string INIPath)
        {
            inipath = INIPath;
        }

        public void IniFiles() { }

        /// <summary> 
        /// 写入INI文件 
        /// </summary> 
        /// <param name="Section">项目名称(如 [TypeName] )</param> 
        /// <param name="Key">键</param> 
        /// <param name="Value">值</param> 
        public static void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, inipath);
        }
        /// <summary> 
        /// 读出INI文件 
        /// </summary> 
        /// <param name="Section">项目名称(如 [TypeName] )</param> 
        /// <param name="Key">键</param> 
        public static string IniReadValue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, Key, "", temp, 500, inipath);
            return temp.ToString();
        }
        /// <summary> 
        /// 验证文件是否存在 
        /// </summary> 
        /// <returns>布尔值</returns> 
        public bool ExistINIFile()
        {
            return File.Exists(inipath);
        }
    }
}

7.反射与泛型_DataTable 转 类   的操作类

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CSQueryKing
{
    class DtConvent<T> where T : new()
    {
        public static List<T> DtToClass(DataTable dt)
        {
            List<T> list = new List<T>();
            string tempName = "";
            // 获得此模型的类型   
            Type type = typeof(T);
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性      
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (var pi in propertys)
                {
                    tempName = pi.Name;  // 检查DataTable是否包含此列   
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter (可写属性),如果没有则跳出    
                        if (!pi.CanWrite) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                list.Add(t);
            }
            return list;
        }
    }
}

8.随缘更新0.0     。。。。。。。。。。。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值