一些自己常用到的C#代码

幽浮404
幽浮404 2018年05月24日
  • 在其它设备中阅读本文章

获取数据库表

public DataTable GetDataTable(string sql, string strcoon)
    {
        DataTable dt1 = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(sql, strcoon))
        {
            da.Fill(dt1);
        }
        return dt1;
    }

获取特定进程 CPU 和内存

void fun_get()
    {
        Process[] CurrentProcess = Process.GetProcesses();
        foreach (var item in CurrentProcess)
        {
            if (item.ProcessName == "Work_Server")
            {
                item.Id.ToString();//PID
                cpu.Text = ((Double)(item.TotalProcessorTime.TotalMilliseconds - item.UserProcessorTime.TotalMilliseconds)).ToString();//CPU
                rom.Text = (item.WorkingSet64 / 1024 / 1024).ToString() + "M (" + (item.WorkingSet64 / 1024).ToString() + "KB)";//占用内存
                item.Threads.Count.ToString();//线程
            }
        }

    }

datatable 获取点击的行

DataRow r = (this.BindingContext[dt].Current as DataRowView).Row;

datatable 保存时结束编辑状态

gridView1.CloseEditor();
(this.BindingContext[dt] as CurrencyManager).EndCurrentEdit();

弹出串口选择文件目录

System.Windows.Forms.FolderBrowserDialog folder =new System.Windows.Forms.FolderBrowserDialog();

            if (folder.ShowDialog() == DialogResult.OK)
            {
                str_path = folder.SelectedPath;

            }

单行覆盖写入文件

public void Write(string path, string str_txt)
    {
        FileStream fs = new FileStream(path, FileMode.Create);
        StreamWriter sw = new StreamWriter(fs);
        //开始写入
        sw.Write(str_txt);
        //清空缓冲区
        sw.Flush();
        //关闭流
        sw.Close();
        fs.Close();
    }

读取 txt 文件

public string read(string path)
    {
        StreamReader sr = new StreamReader(path);
        String line="";
        string ss="";
        while ((line = sr.ReadLine() )!= null)
        {
            ss += line;
            //Console.WriteLine(line.ToString());
            //line += sr.ReadLine().ToString();
        }
        sr.Close();
        return ss;
    }

写入

void fun_writlog(string path, string str_txt)
    {
        try
        {
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.WriteLine(System.DateTime.Now.ToString() + ": " + str_txt);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
        catch(Exception ex)
        {

        }
    }

程序运行路径

static string strDir = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
    string str_path_Debug = strDir + "\\debugLog\\" + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";