C#常用代码

C#常用代码

大小端问题解决

将小端的数字读取,转换成浮点数。

FileStream fs;
BinaryReader br;
try
{
    fs = new FileStream(file, FileMode.Open);
    br = new BinaryReader(fs);
}
catch (IOException)
{
    return false;
}

byte[] bytes = br.ReadBytes(4);
Array.Reverse(bytes);
var val = BitConverter.ToSingle(bytes, 0);

br.Close();
fs.Close();

时间转换

// 从时间戳转换成时间对象
var dateTime = DateTimeOffset.FromUnixTimeSeconds(ticks).DateTime;
// 转换为北京时间
sacFileInfo.dateTime = dateTime.AddHours(8);

高精度的科学计算数字转换代码

支持科学计算数字输入形式: 1.2E05 这种格式


ax = decimal.Parse(arrLine[3], System.Globalization.NumberStyles.Float);

时间字符串格式化

/**
 * @brief 获取时间字符串下的毫秒数
 * @param str 时间字符串
 * @return 返回时间传所对应的毫秒数
 * @example
 *   "013407.40" ==> 01:34:07.40
 *    
 * 返回毫秒数:5647400
 */
public static double findTimeStringMS(string str)
{
    var tmp = str;

    tmp = tmp.Insert(2, ":");
    tmp = tmp.Insert(5, ":");

    TimeSpan ts = TimeSpan.Parse(tmp);

    return ts.TotalMilliseconds;
}

List 操作

取出list其中对象的属性值,还可以做去重复点的操作

int cnt = list.Select(r => r.point).Distinct().Count();
// 过滤,筛选出 list 列表
List<MicroSeis> list = origin.Where(d => d.Station.Contains(stationName)).ToList();

字符串格式化


string line = string.Format("{0:0.00} {1:0.00} {2:0.00000}", x, y, p.val);



var val = 3.123456789;

// 保留2位小数
var msg = string.Format("{0:F2}", val);

Console.WriteLine("{0}", msg);

字典定义和遍历

// 定义待转换的 dir 路径 和 线号
Dictionary<string, int> dict = new Dictionary<string, int>()
{
    {
        @"D:\AAA\-10m极距\L1",
        1
    },
    {
        @"D:\AAA\-10m极距\L2",
        2
    },
    {
        @"D:\AAA\-10m极距\L3",
        3
    },
    {
        @"D:\AAA\-10m极距\L4",
        4
    },
    {
        @"D:\AAA\L4-5m极距\L4_电场",
        4
    },
    {
        @"D:\AAA\L4-0.5m极距\L4-0.5",
        4
    }
};

foreach (KeyValuePair<string, int> kvp in dict)
{
    string dir = kvp.Key;
    int lineNo = kvp.Value;

    dmCalculateAndMergeFile(dir, lineNo);

    string msg = "目录:" + dir + "线号:" + lineNo + ",转换成功!";
    Console.WriteLine(msg);
}

计算程序运行时间

using System.Diagnostics;


Stopwatch stopwatch = new Stopwatch();

//  开始监视代码运行时间
stopwatch.Start();



//  停止监视
stopwatch.Stop();

Console.WriteLine("总耗时:{0} ms", stopwatch.Elapsed.TotalMilliseconds);

ListView 使用经验


            listView.Columns.Add("时间", 100, HorizontalAlignment.Left);
            listView.Columns.Add("日志", 500, HorizontalAlignment.Left);

// 有这项才会显示标题
            listView.View = View.Details;

// 添加日志
            ListViewItem item = new ListViewItem();

            item.Text = "8:00";
            item.SubItems.Add(msg);

            listView.Items.Add(item);

// 始终在首行添加
listView.Items.Insert(0, item);

日期格式化

DateTime dt = DateTime.Now;
item.Text = string.Format("{0:yyyy-MM-dd HH:mm:ss}", dt);

XML字符串解析

            var xml = "<res><stat>1</stat><message>执行成功</message><apply_data>{\"input\":{\"ack_info\":{\"err_msg\":\"\",\"exe_status\":\"A\"},\"kslist\":[{\"dept_id\":\"344\",\"dept_name\":\"fee内分泌科门诊\",\"dept_day\":7],\"rowcount\":[{\"count\":2}],\"bizno\":\"2588\"}}</apply_data></res>";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);

            var json = xmlDoc.GetElementsByTagName("apply_data")[0].InnerXml;
            Console.WriteLine(json);

JSON字符串解析

安装NuGet包:
Newtonsoft.Json


            JObject obj = (JObject)JsonConvert.DeserializeObject(json);
            var status = obj["input"]["ack_info"]["exe_status"].ToString();
            var errMsg = obj["input"]["ack_info"]["err_msg"].ToString();
            Console.WriteLine(status);
            Console.WriteLine(errMsg);

静态构造函数

静态构造函数用于初始化任何静态数据,或执行仅需执行一次的特定操作。 将在创建第一个实例或引用任何静态成员之前自动调用静态构造函数。 静态构造函数最多调用一次。

https://learn.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

线程操作

List<Task> mytasks = new List<Task>();

for (int index = 0; index < n; index++)
{
        mytasks.Add(Task.Factory.StartNew(() => {
            station.starttime = DateTime.Now;

            AlgorithmFilter.Smooth_gauss_Spectrum(station, graphicDisplayParam.spectrum.gaussParam);
        }));

Task.WaitAll(mytasks.ToArray());



Stopwatch stopwatch = new Stopwatch();
stopwatch.Start(); //  开始监视代码运行时间

stopwatch.Stop(); //  停止监视
MessageBox.Show($"{n} 个线程全部完成 , 主线程耗时 {stopwatch.ElapsedMilliseconds} ms , 子线程耗时 {sp}");

    

获取路径下的文件名

var fileName = Path.GetFileName(realDataFile);

获取当前exe所在目录

获取当前exe所在目录

public string root = AppDomain.CurrentDomain.BaseDirectory + "/demo/result";

判断文件所在文件目录是否存在:

DirectoryInfo dir = new DirectoryInfo(importModel.FileDir);
if (!dir.Exists)


str = "获取文件所在的目录:" + Path.GetDirectoryName(filePath)
                DirectoryInfo dir = new DirectoryInfo(dirPath);
                if (!dir.Exists)
                {
                    dir.Create();
                }

// 创建文件夹 
Directory.CreateDirectory(datFolder);


// 获取文件夹下所有文件列表
            DirectoryInfo dirInfo = new DirectoryInfo(dir);

            var files = dirInfo.GetFiles("*.txt");

            if (files.Length <= 0)
            {
                return;
            }

            var file = files.First();

常用文件夹及文件选择操作


OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Filter = string.Format("所有文件|*.*");
// fileDialog.Filter = string.Format("数据文件(*.txt)|*.txt");
// dialog.Filter = "图片(*.png)|*.png";

//若为false,则打开对话框后为上次的目录。若为true,则为初始目录
fileDialog.RestoreDirectory = true;    

if (fileDialog.ShowDialog() != DialogResult.OK)
{
    return;
}
string res = string.Empty;

string[] files = fileDialog.FileNames;

字符串操作

// 替换空白字符
Regex spaceRegex = new Regex("[\\s]+");
line = spaceRegex.Replace(line, " ");

// 分割字符串成数组
char[] arrSep = new[] { ' ', ',', ',' };
string[] arr = line.Split(arrSep, StringSplitOptions.RemoveEmptyEntries);


sunnyui

设置按钮颜色

特别要注意:StyleCustomMode 要设置为 true,切换 Style 才有效果。

序列化与反序列化


            BinaryFormatter formatter = new BinaryFormatter();
            var path = @"d:\area-list.data";

            if (File.Exists(path))
            {
                FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                list = (List<SysArea>)formatter.UnsafeDeserialize(fs, null);
            }
            else
            {
                list = SysArea.Fetch(new Sql());
                using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                {
                    formatter.Serialize(fs, list);
                }

            }

png 转换成 jpg

先读取到png对象里面,再导出到jpg中。


OxyPlot.WindowsForms.PngExporter exporter = new OxyPlot.WindowsForms.PngExporter();
exporter.Width = picWidth;
exporter.Height = picHeight;
exporter.Resolution = dpi;

    Stream stream = new MemoryStream();
    exporter.Export(plotView.Model, stream);

        //静态方式导出
        var filePicName = txtPicTitle.Text + (index++) + ".jpg";
        string picName = new FileInfo(fileName).DirectoryName + "/" + filePicName;
        if (File.Exists(picName))
            File.Delete(picName);
        // JpegExporter.Export(plotView.Model, picName, picWidth, picHeight);
        // JpegExporter.Export(plotModel, fileName, 400, 300);
        var jpeg = picName;
        var img = System.Drawing.Image.FromStream(stream);
        using (var b = new Bitmap(img.Width, img.Height))
        {
            b.SetResolution(img.HorizontalResolution, img.VerticalResolution);
            using (var g = Graphics.FromImage(b))
            {
                g.Clear(Color.White);
                g.DrawImageUnscaled(img, 0, 0);
            }
            b.Save(jpeg, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
posted @ 2023-02-26 15:11  lvye1221  阅读(453)  评论(0编辑  收藏  举报