目 录CONTENT

文章目录

C# function

Jacky
2024-10-22 / 0 评论 / 3 点赞 / 182 阅读 / 14801 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-11-14,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

1.Json数据转换成DataTable 👍

        /// <summary>
        /// Json数据转换成DataTable
        /// </summary>
        /// <remark>
        /// </remark>
        /// <param name="Json"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public DataTable JsonConvertToDataTable(String TableName, String Json)
        {
            DataTable dataTable = new DataTable();
            dataTable.TableName = TableName;
            JArray array = JsonConvert.DeserializeObject(Json) as JArray;
            if (array != null && array.Count > 0)
            {
                StringBuilder columns = new StringBuilder();
                JObject objColumns = array[0] as JObject;
                //构造表头
                //AsEnumerable 引用报错 可以尝试AsJEnumerable
                foreach (JToken jkon in objColumns.AsEnumerable<JToken>())
                {
                    string name = ((JProperty)(jkon)).Name;
                    columns.Append(name + ",");
                    dataTable.Columns.Add(name);
                }
                //向表中添加数据
                for (int i = 0; i < array.Count; i++)
                {
                    DataRow row = dataTable.NewRow();
                    JObject obj = array[i] as JObject;
                    foreach (JToken jkon in obj.AsEnumerable<JToken>())
                    {
                        string name = ((JProperty)(jkon)).Name;
                        string value = ((JProperty)(jkon)).Value.ToString();
                        row[name] = value;
                    }
                    dataTable.Rows.Add(row);
                }
            }
            return dataTable;
        }

2.将JArray转换为datatable 👍

 /// <summary>

        /// 将JArray转换为datatable

        /// </summary>

        /// <param name="dataArr"></param>

        /// <returns></returns>

        public DataTable JArrayToDatable(JArray dataArr)

        {

            if (dataArr == null || dataArr.Count <= 0) return null;

            DataTable result = new DataTable();

            var colnames = ((JObject)dataArr.First).Properties();

            List<string> columnNames = new List<string>();

            if (colnames == null) return null;

            foreach (var item in colnames)

            {

                if (!columnNames.Contains(item.Name))

                {

                    columnNames.Add(item.Name);

                }

                result.Columns.Add(item.Name, typeof(string));

            }

            foreach (JObject data in dataArr)

            {

                JObject jo = JObject.Parse(data.ToString());

                DataRow row = result.NewRow();

                foreach (var columnName in columnNames)

                {

                    if (jo.Property(columnName) == null)

                    {

                        data.Add(columnName, "");

                        row[columnName] = data[columnName].ToString();

                    }

                    else

                    {

                        row[columnName] = data[columnName].ToString();

                    }

                }

                result.Rows.Add(row);

            }

            return result;

        }

3.DataTable使用Select方法之后,把结果转换成DataTable 👍

/// <summary> 

/// 扩展DataTable Select结果为DataTable

/// </summary> 

/// <remark> 

/// </remark>

public DataTable DataTableSelect(this DataTable me, string where)

{

    if(me  null || me.Rows.Count  0) return me;

    var dtNew = me.Clone();

    var drArray = me.Select(where);

    foreach(var item in drArray)

    dtNew.Rows.Add(item.ItemArray);

    return dtNew;

}

4. dot net core读取appsettings.json配置 👍

/// <summary>

        /// 读取配置信息

        /// </summary>

        /// <remarks>

        /// </remarks>

        /// <typeparam name="T"></typeparam>

        /// <param name="name"></param>

        /// <returns></returns>

        public static T Getconfig<T>(string name) where T : class, new()

        {

            IConfiguration config = new ConfigurationBuilder().Add(new JsonConfigurationSource

            {

                Path = "appsettings.json",

                ReloadOnChange = true

            }).Build();

            var appconfig = new ServiceCollection().AddOptions().Configure<T>(config.GetSection(name)).BuildServiceProvider().GetService<IOptions<T>>().Value;

            return appconfig;

        }

5.Socket获取以太网IP(会筛掉虚拟网卡)👍

/// <summary>

/// 通过socket获取IP

/// </summary>

/// <returns></returns>

public static string SocketGetIp()

{

    string localIP = string.Empty;

    using(Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))

    {

        socket.Connect("8.8.8.8", 65530);

        IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;

        localIP = endPoint.Address.ToString();

    }

    return localIP;

}

6.Dns获取IP(只获取IP V4的外网IP) 😄

public static void SocketGetIp()

{

    string localIP = string.Empty;

    using(Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))

    {

        socket.Connect("8.8.8.8", 65530);

        IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;

        localIP = endPoint.Address.ToString();

    }

    Console.WriteLine("IP Address = " + localIP);

}

7.Network获取外网IP 😄

public static void NetworkGetIp()

{

    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

    foreach(NetworkInterface adapter in nics)

    {

        bool Pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet); //判断是否是以太网连接

        if(Pd1)

        {

            Console.WriteLine("网络适配器名称:" + adapter.Name);

            Console.WriteLine("网络适配器标识符:" + adapter.Id);

            Console.WriteLine("适配器连接状态:" + adapter.OperationalStatus.ToString());

            IPInterfaceProperties ip = adapter.GetIPProperties(); //IP配置信息

            if(ip.UnicastAddresses.Count > 0)

            {

                Console.WriteLine("IP地址:" + ip.UnicastAddresses.Where(d => d.IsDnsEligible == true).FirstOrDefault().Address.ToString());

                //Console.WriteLine("IP地址:" + ip.UnicastAddresses[0].Address.ToString());

                Console.WriteLine("子网掩码:" + ip.UnicastAddresses[0].IPv4Mask.ToString());

            }

            if(ip.GatewayAddresses.Count > 0)

            {

                Console.WriteLine("默认网关:" + ip.GatewayAddresses[0].Address.ToString()); //默认网关

            }

            int DnsCount = ip.DnsAddresses.Count;

            Console.WriteLine("DNS服务器地址:"); //默认网关

            if(DnsCount > 0)

            {

                //其中第一个为首选DNS,第二个为备用的,余下的为所有DNS为DNS备用,按使用顺序排列

                for(int i = 0; i < DnsCount; i++)

                {

                    Console.WriteLine("              " + ip.DnsAddresses[i].ToString());

                }

            }

            Console.WriteLine("网络接口速度:" + (adapter.Speed / 1000000).ToString("0.0") + "Mbps");

            Console.WriteLine("接口描述:" + adapter.Description);

            Console.WriteLine("适配器的媒体访问控制 (MAC) 地址:" + adapter.GetPhysicalAddress().ToString());

            Console.WriteLine("该接口是否只接收数据包:" + adapter.IsReceiveOnly.ToString());

            Console.WriteLine("该接口收到的字节数:" + adapter.GetIPv4Statistics().BytesReceived.ToString());

            Console.WriteLine("该接口发送的字节数:" + adapter.GetIPv4Statistics().BytesSent.ToString());

            Console.WriteLine("该接口丢弃的传入数据包数:" + adapter.GetIPv4Statistics().IncomingPacketsDiscarded.ToString());

            Console.WriteLine("该接口丢弃的传出数据包数:" + adapter.GetIPv4Statistics().OutgoingPacketsDiscarded.ToString());

            Console.WriteLine("该接口有错误的传入数据包数:" + adapter.GetIPv4Statistics().IncomingPacketsWithErrors.ToString());

            Console.WriteLine("该接口有错误的传出数据包数:" + adapter.GetIPv4Statistics().OutgoingPacketsWithErrors.ToString());

            Console.WriteLine("该接口协议未知的数据包数:" + adapter.GetIPv4Statistics().IncomingUnknownProtocolPackets.ToString());

            Console.WriteLine("---------------------------------------------------------------------\n");

        }

    }

}

8.校验datatable中被更改的列 👍

/// <summary>

        /// 校验datatable中被更改的列

        /// </summary>

        /// <param name="dt">验证的datatable</param>

        /// <returns>FiledName 字段名称 OldValue 改之前的值 NewValue 修改后的值</returns>

        public static List<object> CheckDataTableColumnChange(DataTable dt)

        {

            if (dt == null || dt.Rows == null || dt.Rows.Count == 0) return null;

            //获取datatable中所有的列名称

            List<string> columnList = new List<string>();

            foreach (DataColumn dc in dt.Columns)
            {

                columnList.Add(dc.ColumnName);

            }

            List<object> checkList = new List<object>();

            foreach (DataRow dataRow in dt.Rows)

            {

                //使用列名称进行匹配

                foreach (var item in columnList)

                {

                    var a = dataRow[item];

                    string oldVal = dataRow[item, DataRowVersion.Original]?.ToString();

                    string newVal = dataRow[item, DataRowVersion.Current]?.ToString();

                    if (!oldVal.Equals(newVal))

                    {

                        checkList.Add(new

                        {

                            FieldName = item,

                            OldValue = oldVal,

                            NewValue = newVal

                        });

                    }

                }

            }

            return checkList;

        }

9.文件加密👍

/// <summary>

/// 文件加密

/// </summary>

/// <param name="inputFile">要加密的文件路径</param>

/// <param name="outputFile">加密后的文件存放路径</param>

public static void EncryptFile(string inputFile, string outputFile)   //加密

{

    try

    {

        string password = @"12345678";

        UnicodeEncoding UE = new UnicodeEncoding();

        byte[] key = UE.GetBytes(password);

        string cryptFile = outputFile;

        FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

        RijndaelManaged RMCrypto = new RijndaelManaged();

        CryptoStream cs = new CryptoStream(fsCrypt,

            RMCrypto.CreateEncryptor(key, key),

            CryptoStreamMode.Write);

        FileStream fsIn = new FileStream(inputFile, FileMode.Open);

        int data;

        while ((data = fsIn.ReadByte()) != -1)

            cs.WriteByte((byte)data);

        fsIn.Close();

        cs.Close();

        fsCrypt.Close();

        Console.WriteLine("Encrypt Source file succeed!");

    }

    catch (Exception ex)

    {

        Console.WriteLine("Source file error! Error :" + ex.Message);

    }

}

10.文件解密👍

 /// <summary>

/// 文件解密

/// </summary>

/// <param name="inputFile">要解密的文件路径</param>

/// <param name="outputFile">解密后的文件存放路径</param>

public static void DecryptFile(string inputFile, string outputFile)   //解密

{

    try

    {

        string password = @"12345678";

        UnicodeEncoding UE = new UnicodeEncoding();

        byte[] key = UE.GetBytes(password);

        FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

        RijndaelManaged RMCrypto = new RijndaelManaged();

        CryptoStream cs = new CryptoStream(fsCrypt,

            RMCrypto.CreateDecryptor(key, key),

            CryptoStreamMode.Read);

        FileStream fsOut = new FileStream(outputFile, FileMode.Create);

        int data;

        while ((data = cs.ReadByte()) != -1)

            fsOut.WriteByte((byte)data);

        fsOut.Close();

        cs.Close();

        fsCrypt.Close();

        Console.WriteLine("Decrypt Source file succeed!");

    }

    catch (Exception ex)

    {

        Console.WriteLine("Source file error! Error :" + ex.Message);

    }

}

11.执行cmd命令

//执行命令        
public void DoComand() {
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                UseShellExecute = false,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8
            };
            string command = "dotnet --version";
            using (Process process = new Process { StartInfo = psi })
            {
                process.StartInfo.Arguments = $"/c {command} /n";
                process.Start();
                string commandResult = process.StandardOutput.ReadToEnd();
                Console.WriteLine(commandResult);
            }
}

3

评论区