【C#】笔记本

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/catshitone/article/details/42145581

1.重命名文件

vb.net中有My.Computer.FileSystem.RenameFile这个方法 但是在C#中如何使用呢?? 其实很简单 只需以下几步 

1.先添加引用:Microsoft.VisualBasic,再加上using Microsoft.VisualBasic.Devices;

2.就下面两行                

Computer MyComputer = new Computer();                
MyComputer.FileSystem.RenameFile(FileName, newFileName); 

其中FileName是你所要重命名的文件的全路径,newFileName仅仅是目标文件名;

2.获取文件的文件名和扩展名

Path.GetFileName(path);//获取文件名
Path.GetExtension(path);//获取扩展名

扩展名包括点,如:.doc

3.删除时的确认框

if (MessageBox.Show("确定删除吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)

4.将一个文件夹中所有的文件包括子文件夹中的文件复制到另一个文件夹中(文件遍历)

 /// <summary>
        /// 复制文件夹下所有文件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        private void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            if (source.FullName.ToLower() == target.FullName.ToLower())
            {
                return;
            }

            // Check if the target directory exists, if not, create it.
            if (Directory.Exists(target.FullName) == false)
            {
                Directory.CreateDirectory(target.FullName);
            }

            // Copy each file into it's new directory.
            foreach (FileInfo fi in source.GetFiles())
            {
                //txtStatue.Text += "复制文件" + target.FullName + "到" + fi.Name;
                
                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }

            // Copy each subdirectory using recursion.
            foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
            {
                DirectoryInfo nextTargetSubDir =
                    target.CreateSubdirectory(diSourceSubDir.Name);
                CopyAll(diSourceSubDir, nextTargetSubDir);
            }
        }

调用方法:

DirectoryInfo source= new DirectoryInfo(@"c:\Template");
            DirectoryInfo target = new DirectoryInfo(@"c:\Done");
            CopyAll(source,target);

5.更改groupbox的边框和字体颜色

private void groupBox1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(groupBox1.BackColor);
            e.Graphics.DrawString(groupBox1.Text, groupBox1.Font, Brushes.Black, 10, 1);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Black, e.Graphics.MeasureString(groupBox1.Text, groupBox1.Font).Width + 8, 7, groupBox1.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Black, 1, 7, 1, groupBox1.Height - 2);
            e.Graphics.DrawLine(Pens.Black, 1, groupBox1.Height - 2, groupBox1.Width - 2, groupBox1.Height - 2);
            e.Graphics.DrawLine(Pens.Black, groupBox1.Width - 2, 7, groupBox1.Width - 2, groupBox1.Height - 2);
        }

6.string不足位数补0

int i=10;
方法1:Console.WriteLine(i.ToString("D5"));
方法2:Console.WriteLine(i.ToString().PadLeft(5,'0'));//推荐
方法3:Console.WriteLine(i.ToString("00000")); 

在 C# 中可以对字符串使用 PadLeft 和 PadRight 进行轻松地补位。


PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度
PadLeft(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度
示例:
h = h.PadLeft(2, '0');

注意第二个参数为 char 类型,所以用单引号,也可以用 Convert.ToChar(string value) 把字符串转换成 char 类型。如果字符串长度大于 1,则使用 str.ToCharArray()[index]。  

7.MDI 子窗体被父窗体控件挡住

using System.Runtime.InteropServices;

[DllImport("user32")]
public static extern int SetParent(int hWndChild, int hWndNewParent);

  Form2 f2 = new Form2();
  f2.MdiParent = this;
  f2.Show();
  SetParent((int)f2.Handle, (int)this.Handle);

此方法有个副作用,就是会导致子窗体的 activated和deactivated等事件失效。

8.Messagebox对话框

if (MessageBox.Show("确定删除吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
MessageBox.Show("数据库中已存在此物品。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

9.16进制与10进制的转换

转16进制

material = cboMaterial.SelectedIndex.ToString("x2");//x表示是16进制  2表示保留两位

转十进制

txtWarhouse.Text = Convert.ToInt32(EPC.Substring(0, 2), 16).ToString();

10.DateTime.Now.ToString()都有哪些样式

 /*
             * 下面各个字母表示的意思:
             * 小写的y表示年份,个数可自由组合,四个y及以上表示2017,三个表示017,两个表示17,一个表示7。大写的Y没有任何意义。
             * 大写的M表示月份,小写的m表示分钟。个数也可自由组合,原理同上。
             * 小写的d表示日期,大写的D无意义。个数可自由组合。
             * 小写的h表示小时,是12小时制。大写H表示24小时制。个数可自由组合。
             * s表示秒。S没意义。
             * f表示毫秒(类似毫秒),后面跟的f越多精度越高,一般只跟3位。不区分大小写。
             * 
             */
            DateTime datetime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);//设置几几年几月1号
            Console.WriteLine(datetime);
            Console.WriteLine(DateTime.UtcNow);//格林威治时间  不依时区而改变
            Console.WriteLine(DateTime.Now.ToUniversalTime());//格林威治时间
            Console.WriteLine(DateTime.Now.ToLocalTime());//本地时间 东八区
            Console.WriteLine(DateTime.Now);//本地时间  东八区
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffff"));
            Console.WriteLine(DateTime.Now.ToString("yyyy-MMM"));//若是系统是中文输出:2017-7月, 若是英文输出:2017-Jul。(简称)(3个M)
            Console.WriteLine(DateTime.Now.ToString("yyyy-MMMMM"));//若是系统是中文输出:2017-七月, 若是英文输出:2017-July。(全称)(3个以上M)
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-ddd"));//若是系统是中文输出:2017-07-周三, 若是英文输出:2017-07-Wed。(简称)(3个d)
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dddd"));//若是系统是中文输出:2017-07-星期三, 若是英文输出:2017-07-Wednesday。(全称)(3个d)
            Console.WriteLine(DateTime.Now.AddDays(-177).ToString());//当前时间减去177天之后的时间

输出:

11.更改groupbox的边框及字体颜色

在groupbox的paint的事件中添加如下:

        private void groupBox3_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(groupBox3.BackColor);
            e.Graphics.DrawString(groupBox3.Text, groupBox3.Font, Brushes.Blue, 10, 1);
            e.Graphics.DrawLine(Pens.Blue, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Blue, e.Graphics.MeasureString(groupBox3.Text, groupBox3.Font).Width + 8, 7, groupBox3.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Blue, 1, 7, 1, groupBox3.Height - 2);
            e.Graphics.DrawLine(Pens.Blue, 1, groupBox3.Height - 2, groupBox3.Width - 2, groupBox3.Height - 2);
            e.Graphics.DrawLine(Pens.Blue, groupBox3.Width - 2, 7, groupBox3.Width - 2, groupBox3.Height - 2); 
        }

12.让textbox控件只能输入数字

在 其keypress事件中添加:

 private void txtWarnValue_KeyPress(object sender, KeyPressEventArgs e)
        {
            //(char)8是退格键
            if (!(char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                //不是数字
                e.Handled = true;
                
            }
        }

13.打开一个文件,获取文件信息

private void button1_Click(object sender, EventArgs e)
        {
            //获取文件的全路径
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;//设置只能为单选

            ofd.Filter = "图片文件|*.jpg;*.jpeg;*.bmp;*.png;*.gif;*.ico";
            if (ofd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                string file = ofd.FileName;
                txtIntroduPath.Text = file;

                txtIntroduPath.Tag = Path.GetExtension(txtIntroduPath.Text);//将文件的扩展名放到tag中
            }
            //自定义的上传接口WebService
            UploadHelper upload = new UploadHelper();
            if (upload.Upload(txtIntroduPath.Text))
            {
                MessageBox.Show("成功");
            }
            else
            {
                MessageBox.Show("shiba");
            }
        }

WebService接口代码:

 public class Service1 : System.Web.Services.WebService
    {

        public byte[] ConvertStreamToByteBuffer(Stream s)
        {
           
            MemoryStream ms = new MemoryStream();
            int b;
            while ((b = s.ReadByte()) != -1)
            {
                ms.WriteByte((byte)b);
            }
            return (ms.ToArray());
        }


        /*上传文件至WebService所在服务器的方法,这里为了操作方法,文件都保存在UpDownFile服务所在文件夹下的UploadFiles目录中 */
        [WebMethod]
        public bool Up(byte[] data, string filename)
        {
            try
            {
                FileStream fs = File.Create(Server.MapPath("/UploadFiles/") + filename);
                fs.Write(data, 0, data.Length);
                fs.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }


        /*下载WebService所在服务器上的文件的方法 */
        [WebMethod]
        public byte[] Down(string filename)
        {
            string filepath = Server.MapPath("/UploadFiles/") + filename;
            if (File.Exists(filepath))
            {
                try
                {
                    FileStream s = File.OpenRead(filepath);
                    return (ConvertStreamToByteBuffer(s));
                }
                catch
                {
                    return (new byte[0]);
                }
            }
            else
            {
                return (new byte[0]);
            }
        }

14.两个日期类型比较大小

int i=DateTime.Compare(DateTime t1, DateTime t2);

返回一个有符号的数。

    1.如果t1比t2时间早则返回一个小于0的数,一般是-1。(如:t1是2005年,t2是2008年)

    2.如果二者时间相同,则返回0.

    3.如果t1比t2晚的话则返回一个大于0的数,一般是1。

15.删除文件夹中,名字为特定字符串的所有文件。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
      
        static void Main(string[] args)
        {
            string path = @"D:\Test";
            DirectoryInfo folder = new DirectoryInfo(path);

            foreach (FileInfo file in folder.GetFiles("*.*"))
            {
                //Console.WriteLine(file.FullName);
                Console.WriteLine(file.Name);//文件名
                if (file.Name.Contains("数据库表"))
                {
                    File.Delete(file.FullName);//文件的全路径名
                    
                }
                
            }
            Console.WriteLine("查询结束");
            Console.Read();
        }
    }
}

16.winform获取当前exe的路径

用Assembly.GetExecutingAssembly(),不要用Directory.GetCurrentDirectory(),这个可能会变

或者用AppDomain.CurrentDomain.BaseDirectory 

17.winform中配置文件app.config的读写操作。

添加system.configruation引用

写入操作:

Configuration cfa =
  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // cfa.AppSettings.Settings["connstr"].Value = cboConnectList.Text;
            cfa.AppSettings.Settings["namespace"].Value = txtNameSpace.Text;
            cfa.AppSettings.Settings["savepath"].Value = txtOutPutDir.Text;
            cfa.Save();

读取操作:

txtNameSpace.Text = ConfigurationManager.AppSettings["namespace"];
            txtOutPutDir.Text = ConfigurationManager.AppSettings["savepath"];

18.线程间通讯。

   在wpf或者winform中,因为有invoke方法存在,所以UI线程和子线程间的通讯实现起来比较简单。但是如果两个线程间没有UI线程,也没有Invoke该怎么通讯呢?

   可以使用SynchronizationContext这个类,它有点类似于android里的handle类。

在线程A中进行声明:

private SynchronizationContext mainThreadSynContext = SynchronizationContext.Current;

在线程B中进行使用:

mainThreadSynContext.Post(new SendOrPostCallback(method), obj);

其中method是方法名,此方法在线程A中定义。obj是自定义的状态,一般我都用来传递method需要的参数。
 

19.格式化分区

只要将Driverletter传入即可,如C:

bool FormatDrive(string driveLetter, string label = "", string fileSystem = "NTFS", bool quickFormat = true, int? clusterSize = 8192,  bool enableCompression = false)
        {
            if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0]))
                return false;
            bool success = false;
            try
            {
                var di = new DriveInfo(driveLetter);
                var psi = new ProcessStartInfo();
                psi.FileName = "format.com";
                psi.WorkingDirectory = Environment.SystemDirectory;
                psi.Arguments = "/FS:" + fileSystem +
                                             " /Y" +
                                             " /V:" + label +
                                             (quickFormat ? " /Q" : "") +
                                             ((fileSystem == "NTFS" && enableCompression) ? " /C" : "") +
                                             (clusterSize.HasValue ? " /A:" + clusterSize.Value : "") +
                                             " " + driveLetter;
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardInput = true;
                var formatProcess = Process.Start(psi);
                var swStandardInput = formatProcess.StandardInput;
                swStandardInput.WriteLine();
                formatProcess.WaitForExit();
                success = true;
            }
            catch (Exception) { }
            return success;
        }

20.winform DesignMode值有时候不正确的问题

DesignMode存在bug,在构造函数里面DesignMode永远都是false,微软对此的 Bug 描述:http://support.microsoft.com/?scid=kb;zh-cn;839202&x=10&y=15.

建议 : 如果你的控件继承自Form或者UserControl,建议重载OnLoad; - 如果继承自Control,可以重载OnCreateControl

猜你喜欢

转载自blog.csdn.net/catshitone/article/details/42145581
今日推荐