C#个人学习笔记

C#个人笔记

1.保存TextBox中内容:

 SaveFileDialog SaveFile = new SaveFileDialog();
 // SaveFile.InitialDirectory = "E:\\1work\\FILE";//初始目录
 SaveFile.Filter = "All files(*.*)|*.*|txt files(*.txt)|*.txt";//文本筛选
 SaveFile.FilterIndex = 3;//文本筛选器索引,选择第一项就是1
 SaveFile.RestoreDirectory = true;
 if (SaveFile.ShowDialog() == DialogResult.OK)
 {
       string resultFile;// = AppDomain.CurrentDomain.BaseDirectory + @"\Config.txt";
       resultFile = SaveFile.FileName;
       StreamWriter sw = File.CreateText(resultFile);
       sw.WriteLine(DateTime.Now.ToString());
       sw.Write(txGet.Text);
       sw.Close();
  }

2.修改文件的修改日期:

string file_path = @"C:\log\sys.txt";
FileInfo file = new FileInfo(file_path);
file.LastWriteTimeUtc = DateTime.Now;

3.窗体最大化,最小化:

this.Windowstate = FormWindowState.Minimized;
this.Windowstate = FormWindowState.Maximized;
this.Windowstate = FormWindowState.Normal;

4.使用代码主动去调用控件的点击事件:

performClick();

5.设置窗体不能鼠标缩小:

this.MinimumSize = this.size;

6.把键盘输入的‘+’符号变成‘A’?
textBox的KeyPress事件中

if(e.KeyChar == '+') 
{ 
    SendKeys.Send("A"); 
    e.Handled = true; 
} 

7.数据转换
(1)整型转换成二进制字符串:string str = Convert.ToString(value, 2).PadLeft(8,‘0’);
(2)整型转换成八进制字符串:string str = Convert.ToString(value, 8).PadLeft(3,‘0’);
(3)整型转换成十六进制字符串:string str = value.ToString(“X2”);
(4)十六进制字符串转换成整型:int value = Convert.ToInt32(str,16);
(5)获取Ascii码:
int asciiCode;
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] byteArray = new byte[] { (byte)asciiCode };
string strCharacter = asciiEncoding.GetString(byteArray);

8.整型转四个byte

uint i = 0x7a7a7a;
byte[] Buff = BitConverter.GetBytes(i);

9.C# 中object sender与EventArgs e
object是一个对象(其实这里传递的是对象的引用,如果是button1的click事件则sender 就是button1);
EventArgs是包含事件数据的类的基类,用于传递事件的细节:
什么叫做事件数据?
最简单的:鼠标点击事件
那么左键、中键还是右键? 点击的位置坐标等信息 需要传递给事件响应者对吧
这些就是事件的数据(因为你在响应该事件时对这些数据感兴趣)
什么叫做事件数据的基类?
EventArgs就是 所有的事件数据类都要继承该类
比如鼠标事件数据类
public class MouseEventArgs : EventArgs

10.自定义控件添加属性和描述到属性栏:

[Browsable(true)]		//是否显示在属性栏中
[Description("默认选中的复选框!"),Category("自定义属性"),DefaultValue(0)]		//在属性栏中的描述
public int CheckIndex { get; set; }

在这里插入图片描述
11.窗体容器中内嵌窗体:

//首先判断当前容器中是否已经存在窗体
    foreach(Control item in this.spContainer,Panel2.Controls)
    {
   		 	if(item is Form)
    		{
    			Form objControl=(Form)item;
    			objControl.Close();
    		}
    		FrmAddStudent objFrm = new FrmAddStudent();
    		objFrm.TopLevel = false;//将子窗体设置成非顶级控件
    		objFrm.WindowsState = FormWindowsStat.Maximized;//让子窗体最大化显示
    		objFrm,FormBorderStyle = FormBorderStyle.None;//去掉窗体边框
    		objFrm.Parent = this.spContainer.Panel2;//指定子窗体显示的容器
   			objFrm.Show();
    }

12.ADO.Net连接数据库

string connString = "Server=.;DataBase=StudentManageDB;Uid=sa;Pwd=123456";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
if(conn.State == ConnectionState.Open)
{
      Console.WriteLine("Connection is opened");
}
      conn.Close();
if(conn.State == ConnectionState.Closed)
{
      Console.WriteLine("Connection is closed");
}
Console.ReadLine();

13.将异常写入日志:

try
{
	//Code
}
catch (Exception ex)
{
     string LogAddress = "log.txt";
     StreamWriter fs = new StreamWriter(LogAddress, true);
     fs.WriteLine("当前时间:" + DateTime.Now.ToString());
     fs.WriteLine("异常信息:" + ex.Message);
     fs.WriteLine("异常对象:" + ex.Source);
     fs.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
     fs.WriteLine("触发方法:" + ex.TargetSite);
     fs.WriteLine();
     fs.Close();
}

14.ADO.NET
Select count(*) from 返回的是当前表中数据的条数,
Select * from返回的是当前表中所有的数据;

15.Winform获取电脑屏幕的大小:

int iActulaWidth = Screen.PrimaryScreen.Bounds.Width;  
int iActulaHeight = Screen.PrimaryScreen.Bounds.Height ;

  System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width   
  System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height

Screen.PrimaryScreen.WorkingArea.Height;
Screen.PrimaryScreen.WorkingArea.Width;

16.获取时间转固定格式:

string str = DateTime.Now.ToString("yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo);

17.webBrowser控件打开本地网页文件:

webBrowser1.Navigate(Application.StartupPath + @"\Test.html");

18.获取一个文本文档的行数:

int GetRows(string FilePath)
{
	using (StreamReader read = new StreamReader(FilePath, Encoding.Default))
	{
		return read.ReadToEnd().Split('\n').Length;
	}
}

19.设置TreeView节点的索引图标
要在目录中使用图标首先要加入一个控件ImageList(命名为imageList1),然后可以按图片的index或名称引用图片.
然后需要在TreeView控件的ImageList属性中指向imageList1.
TreeView有两个属性:
SelectImageIndex:选中该结点时显示的图片的索引
ImageIndex:未选中该结点时显示的图片的索引
可以实现的效果是,选中某个结点时该结点的图片进行改变,如果我们的目标也是如此,万事已经大吉了.
但我希望的效果是:展开某个结点时该结点的图片改变(如显示为打开的盒子),折叠时该结点的图片改变(如包装好的盒子).直接使用属性无法实现该效果.
实现原理是:展开某个结点时将SelectImageIndex和ImageIndex统统指向打开盒子的图片
折叠某个结点时将SelectImageIndex和ImageIndex统统指向包装盒子的图片
自然需要用到两个事件:TreeView的AfterExpand和AfterCollapse事件

   private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
    {
        e.Node.ImageIndex = 1; //指向展开的图标
        e.Node.SelectedImageIndex = 1;//指向展开的图标
    }

    private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e)
    {
        e.Node.ImageIndex = 0; //指向关闭的图标
        e.Node.SelectedImageIndex = 0;//指向关闭的图标
    }

20.语法高亮编辑器比拼
https://www.cnblogs.com/Impulse/articles/6210328.html

21.子窗体只能打开一个,并且与主窗体并列显示:

private void button1_Click(object sender, EventArgs e)
{
       if (objFrm == null)
       {
             objFrm = new Form2(this.Location.X + this.ClientSize.Width, this.Location.Y);
             objFrm.Show();
       }
       else
       {
              if (objFrm.IsDisposed)
              {
                    objFrm = new Form2(this.Location.X + this.ClientSize.Width, this.Location.Y);
                    objFrm.Show();
              }
              objFrm.Activate();
        }
}

Form2:有参构造函数,设置窗体属性StartPosition = Manual;

public Form2(int x,int y):this()
{
        this.Location = new Point(x,y);
}

22.TextBox控件显示默认文本点击消失离开显示

private void textBox1_Enter(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == "请输入密码")
            {
                textBox1.ForeColor = ColorTranslator.FromHtml("#333333");
                textBox1.Text = "";
                textBox1.PasswordChar = '*';
            }
        }
    private void textBox1_Leave(object sender, EventArgs e)
    {
        if (textBox1.Text.Trim().Length == 0)
        {
            textBox1.ForeColor = ColorTranslator.FromHtml("#999999");
            textBox1.PasswordChar = '\0';
            textBox1.Text = "  请输入密码";
        }
    }

23.控件的ImeMode属性:设定输入法;
在这里插入图片描述
24.RichTextBox以指定编码格式加载文件内容

richTextBox1.Text = System.IO.File.ReadAllText(fileName, System.Text.Encoding.GetEncoding("GB2312"));

25.C#加载配置文件App.config内的信息:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="Version" value="V1.2"/>
  </appSettings>
  <connectionStrings>
    <add name="connString" connectionString="Server=.;DataBase=SMDB;Uid=sa;Pwd=123456"/>
  </connectionStrings>
</configuration>

添加引用:using System.Configuration;

string ver  = ConfigurationManager.AppSettings["Version"];
private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();

26.C#嵌入资源的读取

  1. 右键点击项目,选择资源,然后选择资源的类型,插入资源。

  2. 这时候在项目的目录树上会出现一个Resource的文件夹,找到嵌入的资源文件,右击属性,在 Build Action 属性,将类型改为 Embedded Resource,然后保存。

  3. 编辑读取资源的代码

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
string fileName = assembly.GetName().Name + ".Resources.YOUR_FILE_NAME";
System.IO.Stream stream= Asmb.GetManifestResourceStream(fileName);
 
byte[] StreamData = new byte[stream.Length];
stream.Read(StreamData, 0, (int)stream.Length);  
 
Console.WriteLine(System.Text.Encoding.ASCII.GetString(StreamData));

资源的路径规则是:项目命名空间.资源文件所在文件夹名.资源文件名

27.C#创建文件写数据:

string mylog = "test_log_" + DateTime.Now.ToString("yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo) + ".xls";
FileStream fs = new FileStream(mylog, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
string msg =12345”;
sw.WriteLine(msg);
sw.Close();
fs.Close();

或者先判断文件夹内是否有同名的文件,如果有累加:

string path = System.AppDomain.CurrentDomain.BaseDirectory;
string filename="";
for (int j = 0; j < 100; j++)
{
    filename = string.Format("Rec{0}.txt", j.ToString().PadLeft(3,'0'));
    if (!File.Exists(path + filename))
                    break;
 }
 Console.WriteLine(filename);
 Console.ReadKey();

28.计算代码运行时间

//导入该命名空间
using System.Diagnostice;
Stopwatch watch=new Stopwatch ();
watch.Start();
/*
此处为要计算的运行代码
*/
watch.Stop();
//获取当前实例测量得出的总运行时间(以毫秒为单位)
string time = watch.ElapsedMilliseconds.ToString();

29.根据日期计算星期

protected void Page_Load(object sender, EventArgs e)
{
    int m = System.DateTime.Today.Month;
    int y = System.DateTime.Today.Year;
    int d = System.DateTime.Today.Day;
    int weeks = getWeekDay(y, m, d);
    switch (weeks)
    {
      case 1:
        this.TextBox1.Text = "星期一";
        break;
      case 2:
        this.TextBox1.Text = "星期二";
        break;
      case 3:
        this.TextBox1.Text = "星期三";
        break;
      case 4:
        this.TextBox1.Text = "星期四";
        break;
      case 5:
        this.TextBox1.Text = "星期五";
        break;
      case 6:
        this.TextBox1.Text = "星期六";
        break;
      case 7:
        this.TextBox1.Text = "星期日";
        break;
    }
}
/// <summary>根据日期,获得星期几</summary>
/// <param name="y">年</param>
/// <param name="m">月</param>
/// <param name="d">日</param>
/// <returns>星期几,1代表星期一;7代表星期日</returns>
public static int getWeekDay(int y, int m, int d)
{
    if (m == 1) m = 13;
    if (m == 2) m = 14;
    int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7 + 1;
    return week;
}

30.删除文件夹

/// <summary>
/// C# 删除文件夹
/// 用法: DeleteFolder(@"c:\\1");
/// </summary>
/// <param name="dir"></param>
private static void DeleteFolder(string dir)
{
  // 循环文件夹里面的内容
  foreach (string f in Directory.GetFileSystemEntries(dir))
  {
  // 如果是文件存在
  if (File.Exists(f))
  {
  FileInfo fi = new FileInfo(f);
  if (fi.Attributes.ToString().IndexOf("Readonly") != 1)
  {
  fi.Attributes = FileAttributes.Normal;
  }
  // 直接删除其中的文件
  File.Delete(f);
  }
  else
  {
  // 如果是文件夹存在
  // 递归删除子文件夹
  DeleteFolder(f);
  }
  }
  // 删除已空文件夹
  Directory.Delete(dir);
}

31.C#版本与.NET版本对应关系以及各版本的特性
在这里插入图片描述
32.C#读取嵌入的txt文件内容;
在这里插入图片描述
读取内容的代码:

string name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".file.txt";
Stream sm = Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
byte[] bs = new byte[sm.Length];
sm.Read(bs, 0, (int)sm.Length);
sm.Close();
UTF8Encoding con = new UTF8Encoding();
string str = con.GetString(bs);
MessageBox.Show(str);

33.使用StringBuilder追加字符串并保存到文本文件中:
方式一:

string filepath = AppDomain.CurrentDomain.BaseDirectory + "Test.txt";
StringBuilder sb = new StringBuilder();
sb.Append("Hello").Append("World!");
using(StreamWriter sw = new StreamWriter(filepath,false,Encoding.GetEncoding("GB2312")))
{
     sw.Write(sb.ToString());
}

方式二:

string filepath = AppDomain.CurrentDomain.BaseDirectory + "Test1.txt";
StringBuilder builder = new StringBuilder();
using (FileStream fsWrite = new FileStream(filepath, FileMode.Create))
{
     builder.Append("Hello" + "\r\n");
     builder.Append("World!" + "\r\n");

     byte[] myByte = System.Text.Encoding.Default.GetBytes(builder.ToString());
     fsWrite.Write(myByte, 0, myByte.Length);
}

34.使用FileStream和StreamWriter往文件中写入数据:

string filepath = AppDomain.CurrentDomain.BaseDirectory + "Test.txt";
FileStream fs = new FileStream(filepath,FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("GOOD JOBS!");
sw.Close();

35.C#在程序的属性=>设置中添加字符串保存程序中的字符串,这里添加了一个Setting1,这里会和App.config文件中的内容相对应:

在这里插入图片描述

//程序关闭的时候保存
private void Form1_FormClosed(object sender, FormClosedEventArgs e) 
{ 
	Settings.Default.Setting1 = this.textBox1.Text; 
	Settings.Default.Save(); 
}
//程序打开的时候显示
public Form1()
{
     InitializeComponent();
     tb_NetAddress.Text = Settings.Default.Setting1;
}

36.C# Winform中TreeView控件的使用:

private void Form1_Load(object sender, EventArgs e)
        {
            string path = "src";
            LoadData(path,treeView1.Nodes);
        }

        private void LoadData(string path,TreeNodeCollection treeNodeCollection)
        {
            //1.获取path下所有文件夹
            string[] dirs = Directory.GetDirectories(path);
            foreach(var item in dirs)
            {
                TreeNode tnode = treeNodeCollection.Add(Path.GetFileName(item));
                LoadData(item,tnode.Nodes);
            }

            //2.获取path下所有的文本文件
            string[] files = Directory.GetFiles(path,"*.C");
            foreach(var item in files)
            {
                TreeNode tnode = treeNodeCollection.Add(Path.GetFileName(item));
                tnode.Tag = item;//利用tag属性来保存文件完整路径
            }
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag != null)
                richTextBox1.Text = File.ReadAllText(e.Node.Tag.ToString(),Encoding.Default);
        }

37.C#大文件拷贝

private static void LargeFileCopy(string sourceFile,string targetFile)
        {
            //1.创建一个读取源文件的文件流
            using(FileStream fsRead = new FileStream(sourceFile,FileMode.Open,FileAccess.Read))
            {
                //2.创建一个写入新文件的文件流
                using(FileStream fswrite = new FileStream(targetFile,FileMode.Create,FileAccess.Write))
                {
                    //创建一个copy文件的中间缓冲区
                    byte[] bytes = new byte[1024 * 1024 * 5];
                    //返回值表示本次实际读取到的字节个数
                    int r = fsRead.Read(bytes,0,bytes.Length);

                    while (r > 0)
                    {
                        //将读取到的内容写入到新文件中
                        //第三个参数应该是实际读取到的字节数,而不是数组的长度
                        fswrite.Write(bytes, 0, r);
                        //显示copy进度百分比
                        double d = (fswrite.Position / (double)fsRead.Length) * 100;
                        Console.WriteLine("{0}%",d);
                        r = fsRead.Read(bytes,0,bytes.Length);
                    }
                }
            }
        }

38.C# 字符串前加$

string s = "hello";
string fo = $"{s} world";

// 等同于使用Format方法:
string fo = string.Format("{0} world",s);

39.C#里面中将字符串转为变量名

public partial class Form1 : Form
{
        string str = "spp";
        public string spp = "very good";

        public Form1()
        {
            InitializeComponent();

            MessageBox.Show(this.GetType().GetField(str).GetValue(this).ToString());
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值