首页 > 代码库 > C#常用代码1

C#常用代码1

1.剪切板:    Clipboard.SetDataObject(textBox1.SelectedText);    2.时间格式:        DateTime time = new DateTime(2015,9,17,9,50,34);        Console.WriteLine(time.ToString("yyyy-MM-dd HH:mm"));    3.连接Mysql字符串:Database="+database+";Data Source=localhost;User Id=root;Password=;CharSet=utf8    4.winform读取配置文件:System.Configuration.ConfigurationSettings.AppSettings["database"]    5.datatable选取单列:        var tablenames = table.AsEnumerable().Select(t => new { TABLE_NAME = t.Field<string>("TABLE_NAME") });                    List<string> tabs = new List<string>();                    foreach (var item in tablenames)                    {                        if (!tabs.Contains(item.TABLE_NAME))                            tabs.Add(item.TABLE_NAME);                      }    6.List<string>批量添加数据:              List<string> biaoshi1 = new List<string>() { "第一条", "第二条", "第三条", "第四条", "第五条" };              biaoshi1.AddRange(new string[] { "第十六条", "第十七条", "第十八条"}.ToList());    7.数组合并:            result.Concat(item);    8.DataTable过滤,增加属性:        1.新增属性: table.ExtendedProperties.Add("errormsg", errorkey);        2.过滤:              rows=MsgTable.Select("准考证号=‘" + ScoreTable.Rows[n]["考号"].ToString().Trim() + "");    9.DataView过滤,排序:         sort_view = ScoreTable.DefaultView;         sort_view.RowFilter = "考号<>‘‘";         sort_view.Sort = "考号 asc";         DataTable scoretab2 = sort_view.ToTable();    10.打开文件:         System.Diagnostics.Process.Start(item.ToString());    11.格式化两位小数:        log_builder.Insert(0,"考生成绩总数:"+ScoreTable.Rows.Count.ToString()+"\r\n可匹配考生数:" + totalcount.ToString() + "\r\n匹配率:" + string.Format("{0:F}", ((decimal)totalcount / (decimal)ScoreTable.Rows.Count)*100) + "%\r\n");    12.正则匹配:        Regex Catalog_regex = new Regex(@"\b第\w*章\b.+\t\b");                    MatchCollection matches = Catalog_regex.Matches(Catalog);                    List<string> Catalog_list = new List<string>();                    if (matches.Count > 0)                    {                        foreach (var item in matches)                        {                            Catalog_list.Add(item.ToString().Replace("\t",""));                        }                    }    13.字符串查找数字:        Regex regex = new Regex(@"\d+");                                        foreach (string item in keys)                    {                        filelist = FBY_libs.Oper.File_Oper.GetFileNames(this.process_textBox.Text.Trim(), "*" + item + "*.XLS", true).ToList();                        foreach (string str in filelist)                        {                            filename = Path.GetFileNameWithoutExtension(str);                            this.result_textBox.Text += filename + "\t\t" + regex.Match(filename).Value+"\r\n";                        }                        this.result_textBox.Text += "\r\n";                                   }    14.主线程休眠:        System.Threading.Thread.Sleep(1000);    15.创建文件夹:         Directory.CreateDirectory(out_path + "\\" + item);    16.Word模板关联数据:         //域参数                    string[] Filed_vars=new string[table.Columns.Count];                    object[] Filed_values = new object[table.Columns.Count];                    for (int n = 0; n < table.Columns.Count; n++)                    {                        Filed_vars[n] = table.Columns[n].ColumnName;                    }                    for (int n = 0; n < table.Rows.Count; n++)                    {                        doc = new Document(templet);                        for (int t = 0; t < table.Columns.Count; t++)                        {                            Filed_values[t] = table.Rows[n][t];                        }                        doc.MailMerge.Execute(Filed_vars, Filed_values);                        doc.Save(out_path+filename+"-"+(n+1).ToString()+".docx",SaveFormat.Docx);                    }    17.Word批量合并:         //合并word                    Document total_doc = new Document(out_path + filename + "-" + "1.docx");                            for (int n = 2; n <= table.Rows.Count; n++)                    {                        doc = new Document(out_path + filename + "-" + n.ToString()+".docx");                                                total_doc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting);                    }                    total_doc.Save(out_path+filename+"-"+"汇总.docx");                    for (int n = 1; n <= table.Rows.Count; n++)                    {                        File.Delete(out_path + filename + "-" + n.ToString() + ".docx");                    }    18.验证文件存在:            if (!File.Exists(this.Catalog_path_textBox.Text.Trim()))                    {                        MessageBox.Show("目录页文件不存在,请检查!","提示");                        return;                    }    19.窗体快捷键:        首先要将form窗体的KeyPreview属性设为True。        if (e.KeyCode == Keys.F1)                    {                        ShowHelp();                    }    20.Dictionary的linq查询:        var sel = from d in dict2.AsEnumerable() where d.Value =http://www.mamicode.com/= row["医师资格证书编码"].ToString() select d.Key;        foreach (int key2 in sel.ToList())                   {                     table.Rows[key2]["当前状态"] = "免考";                    }    21.删除文件及文件夹:         if (Directory.Exists(page_path))                        Directory.Delete(page_path,true);    22.DataTable删除:        datatable.Rows[i].Delete();        Datatable.AcceptChanges();    23.随机List<T>:         public List<T> RandomSortList<T>(List<T> ListT)                  {                      Random random = new Random();                      List<T> newList = new List<T>();                      foreach (T item in ListT)                      {                          newList.Insert(random.Next(newList.Count), item);                      }                      return newList;                  }      24.NPOI设置单元格样式:        if (Convert.ToInt32(t_row.ItemArray[5]) < 60)                                    {                                       ICellStyle cellStyle = result_xls.CreateCellStyle();                                       IFont font=result_xls.CreateFont();                                       font.Color = 10;                                       cellStyle.SetFont(font);                                                                              cell.CellStyle = cellStyle;                                     }    25.Linq查询:          trueanswer = answer.Where(x => x.Option == result["Answer"].ToString()).ToList();

C#常用代码1