zoukankan      html  css  js  c++  java
  • C#:随笔

    生成二维码并显示

    Visual Studio > 右击项目名 > Manage NuGet Packages... > 搜索Spire.Barcode并安装。当前版本是v3.5.0,VS用的是VS Community 2017 Version 15.9.12

    // Program.cs中Main函数内添加如下代码,生成QR Code
    using Spire.Barcode;
    using System.Drawing;
    static void Main(string[] args)
    {
        //创建BarcodeSettings对象
        BarcodeSettings settings = new BarcodeSettings();         
        //设置条码类型为二维码
        settings.Type = BarCodeType.QRCode;
        //设置二维码数据
        settings.Data = "123456789";
        //设置显示文本
        settings.Data2D = "123456789";
        //设置数据类型为数字
        settings.QRCodeDataMode = QRCodeDataMode.Numeric;
        //设置二维码错误修正级别
        settings.QRCodeECL = QRCodeECL.H;
        //设置宽度
        settings.X = 3.0f;
        //实例化BarCodeGenerator类的对象
        BarCodeGenerator generator = new BarCodeGenerator(settings);
        //生成二维码图片并保存为PNG格式
        Image image = generator.GenerateImage();
        image.Save("QRCode.png"); // not mandatory
    }
    
    // Form1.cs,将生成的image参数传递给Form以便显示出来
    public Form1(Image image) // add args image
    {
        InitializeComponent(image); // parse image to form
    }
            
    // Form1.Designer.cs,添加pictureBox用于显示二维码
    using System.Drawing; // add name space if report error
    private void InitializeComponent(Image image) // parse image
    this.pictureBox1.Image = image; // show QRCode
    this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; // AutoSize根据图片的大小自动扩展pictureBox
    

    C#操作字符串

    string.Format("https://www.baidu.com/s?wd={0}_{1}", width, height)
    str=str.Replace("abc","ABC");  // 如果字符串中有"abc"则替换成"ABC"
    string str="123abc456"; int i=3;
    str=str.Substring(0,i); // or  str=str.Remove(i,str.Length-i);  取字符串的前i个字符
    str=str.Remove(0,i);  // or str=str.Substring(i);  去掉字符串的前i个字符
    str=str.Substring(str.Length-i); // or str=str.Remove(0,str.Length-i);  从右边开始取i个字符
    str=str.Substring(0,str.Length-i); // or str=str.Remove(str.Length-i,i);  从右边开始去掉i个字符
    //判断字符串中是否有"abc" 有则去掉之
    using System.Text.RegularExpressions;
    string str = "123abc456";
    string a="abc";
    Regex r = new  Regex(a);
    Match m = r.Match(str);
    if (m.Success)
    {   //绿色部分与紫色部分取一种即可。
        str=str.Replace(a,"");
        Response.Write(str);
        string str1,str2;
        str1=str.Substring(0,m.Index);       str2=str.Substring(m.Index+a.Length,str.Length-a.Length-m.Index);
        Response.Write(str1+str2);
    }
    

    C#中的File类用法

    File.Exists(@"路径"); //判断文件是否存在,返回一个bool值
    File.Move(@"",@""); //剪切
    File.Copy(Symblink + @"EFIBootshel.efi", Symblink + @"EFIBootootx64.efi", true); //复制
    File.Delete(@"",@""); //彻底删除
    File.ReadAllLines(@""); //读取一个文本文件,返回一个字符串数组
    string[] str = File.ReadAllLines(@"C:UsersAdministratorDestopaa.txt",Encoding.Default); // Encoding.Default使用系统默认编码
    for(int i = 0; i < str.Length; i++)
    {     Console.WriteLine(str[i]); }
    File.ReadAllText(@"");//读取一个文本文件,返回一个字符串
    string str = File.ReadAllText(@"C:UsersAdministratorDestopaa.txt",Encoding.UTF8);//Encoding.UTF8使用UTF8编码
    File.ReadAllBytes(@"");//读取一个文件,返回字节数组
    byte[] bt = File.ReadAllBytes(@"C:UsersAdministratorDestopaa.txt"); //将byte数组解码成我们认识的字符串
    for(int i = 0; i < bt.Length; i++)
    {     Console.WriteLine(byte[i].ToString()); }
    File.WriteAllLines(@"");//将一串字符串数组写入到一个文本文件,会覆盖源文件。
    File.WriteAllText(@"");//将一串字符串写入到一个文本文件中,会覆盖源文件。
    File.WriteAllBytes(@"");//将一个字节数组写入到一个文本文件中,会覆盖源文件。
    File.AddAllText(@"");//将一个字符串写入到一个文本文件中,不会覆盖源文件。
    File.AddAllLines(@"");//……,不覆盖源文件。
    File.AddAllBytes(@"");//……,不覆盖源文件。
    //将一个任意类型的文件复制到其他位置 byte[] bt = File.ReadAllBytes(@"C:UsersAdministratorDestopaa.avi"); File.WriteAllBytes(@"D:
    ew.avi",bt);
    File只能操作小文件,操作大文件速度极慢
    

    C#读写改XML

    public static void WriteLogPathToDebugInfo()
    {
        string debugxml =  Path.GetFullPath("../../") + @"LogDebugInfo.xml"; // C:Program Files (x86)AutoRILogDebugInfo.xml
        if (!File.Exists(debugxml)) // XML不存在,创建
        {
            Console.WriteLine(string.Format("Not find {0}, create it", debugxml));
            XmlDocument xmlDoc = new XmlDocument(); // 创建XmlDocument对象
            XmlDeclaration xmlSM = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); // XML的声明 
            xmlDoc.AppendChild(xmlSM); // 追加xmldecl位置
            XmlElement xml = xmlDoc.CreateElement("", "debuginfo", ""); // 添加一个名为debuginfo的根节点
            xmlDoc.AppendChild(xml); // 追加debuginfo的根节点位置
            XmlNode gen = xmlDoc.SelectSingleNode("debuginfo"); // 添加另一个节点,与debuginfo所匹配,查找
            XmlElement zi = xmlDoc.CreateElement("name"); //添加一个名为的节点   
            zi.SetAttribute("type", "BurnIn Test"); //节点的属性
            XmlElement x1 = xmlDoc.CreateElement("logpath");
            x1.InnerText = Path.GetFullPath("../../") + @"LogBurnInTest.log"; //InnerText:获取或设置节点及其所有子节点的串连值
            zi.AppendChild(x1); //添加到节点中
            gen.AppendChild(zi);//添加到节点中   
            xmlDoc.Save(debugxml);//"debuginfo.xml");
        }
        else // XML已经存在,如查找到则修改并置flag
        {
            bool findnode = false;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(debugxml);
    
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("debuginfo").ChildNodes;//获取Employees节点的所有子节点
            foreach (XmlNode xn in nodeList)//遍历所有子节点 
            {
                XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型 
                if (xe.GetAttribute("type") == "BurnIn Test")//如果type属性值为“BurnIn Test” 
                {
                    //xe.SetAttribute("type", "3D Mark11_M");//则修改该属性为“update张三”
                    XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点 
                    foreach (XmlNode xn1 in nls)//遍历 
                    {
                        XmlElement xe2 = (XmlElement)xn1;//转换类型 
                        if (xe2.Name == "logpath")//如果找到 
                        {
                            xe2.InnerText = Path.GetFullPath("../../") + @"LogBurnInTest.log";//则修改
                            Console.WriteLine("Find " + debugxml + @" and BurnIn Test node, write its logpath to C:BurnIn_LogsBIT.log");
                            findnode = true; 
                        }
                    }
                }
            }
            if (findnode == false) // 找不到此Node,添加
            {
                Console.WriteLine("Find " + debugxml + " But NOT find BurnIn Test node, create it and append logpath");
                XmlNode root = xmlDoc.SelectSingleNode("debuginfo"); // 查找 
                XmlElement xe1 = xmlDoc.CreateElement("name"); // 创建一个节点 
                xe1.SetAttribute("type", "BurnIn Test"); // 设置该节点genre属性 
                XmlElement xesub1 = xmlDoc.CreateElement("logpath");
                xesub1.InnerText = Path.GetFullPath("../../") + @"LogBurnInTest.log"; // 设置文本节点 
                xe1.AppendChild(xesub1); // 添加到节点中 
                root.AppendChild(xe1); // 添加到节点中 
            }
            xmlDoc.Save(debugxml); // 保存。
        }
    }
    

    C#获取ini文件中全部Section,获取Section下全部Key

    using System.Runtime.InteropServices;
    [DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
    private static extern uint GetPrivateProfileStringA(string section, string key, string def, Byte[] retVal, int size, string filePath);
    
    static void Main(string[] args)
    {
        string[] sections = ReadSections(@"C:Usersyinguo.li.LCFCDesktopaaaainDebugModules.ini").ToArray();
        string[] keys = ReadKeys("Thermal_TAT", @"C:Usersyinguo.li.LCFCDesktopaaaainDebugModules.ini").ToArray();
        foreach (string section in sections)
            Console.WriteLine(section);
        foreach (string key in keys)
            Console.WriteLine(key);
    }
    
    public static List ReadSections(string iniFilename)
    {
        List result = new List();
        Byte[] buf = new Byte[65536];
        uint len = GetPrivateProfileStringA(null, null, null, buf, buf.Length, iniFilename);
        int j = 0;
        for (int i = 0; i < len; i++)
            if (buf[i] == 0)
            {
                result.Add(Encoding.Default.GetString(buf, j, i - j));
                j = i + 1;
            }
        return result;
    }
    
    public static List ReadKeys(string SectionName, string iniFilename)
    {
        List result = new List();
        Byte[] buf = new Byte[65536];
        uint len = GetPrivateProfileStringA(SectionName, null, null, buf, buf.Length, iniFilename);
        int j = 0;
        for (int i = 0; i < len; i++)
            if (buf[i] == 0)
            {
                result.Add(Encoding.Default.GetString(buf, j, i - j));
                j = i + 1;
            }
        return result;
    }
    

    C#增删数组

    string[] DiskArray = Output.Split('
    ');
    List list = DiskArray.ToList();
    List NewList = new List();
    NewList.Add(line);
    DiskArray = NewList.ToArray();
    

    C#操作系统日志

    var log = new EventLog("System");
    
    var wakeUpEntry = (from entry in log.Entries.Cast<EventLogEntry>()
                        where entry.InstanceId == 41
                        orderby entry.TimeWritten descending
                        select entry).First();
    
    string info = string.Empty;
    info += "类型:" + wakeUpEntry.EntryType.ToString() + ";";
    info += "日期" + wakeUpEntry.TimeGenerated.ToLongDateString() + ";";
    info += "时间" + wakeUpEntry.TimeGenerated.ToLongTimeString() + ";";
    info += "来源" + wakeUpEntry.Source.ToString() + ";";
    info += "时间" + wakeUpEntry.TimeWritten.ToString() + ";";
    
    DateTime startTime = Convert.ToDateTime(DateTime.Now.ToString());
    int dateResult1 = DateTime.Compare(wakeUpEntry.TimeWritten, startTime);
    int dateResult2 = DateTime.Compare(wakeUpEntry.TimeWritten, Convert.ToDateTime("2019 - 10 - 29 14:25:56"));
    Console.WriteLine("{0}, {1}", dateResult1, dateResult2);
    

    Directory 操作文件夹

                    //创建文件夹
                    Directory.CreateDirectory(@"C:a");
                    Console.WriteLine("创建成功");
                    Console.ReadKey();
    
                    //删除文件夹
                    Directory.Delete(@"C:a",true);
                    Console.WriteLine("删除成功");
                    Console.ReadKey();
    
    
                    //剪切文件夹
                    Directory.Move(@"c:a", @"C:UsersSpringRainDesktop
    ew");
                    Console.WriteLine("剪切成功");
                    Console.ReadKey();
    
    
                    //获得指定文件夹下所有文件的全路径
                    string[] path = Directory.GetFiles(@"C:UsersSpringRainDesktopPicture","*.jpg");
                    for (int i = 0; i < path.Length; i++)
                    {
                        Console.WriteLine(path[i]);
                    }
                    Console.ReadKey();
    
    
                    //获得指定目录下所有文件夹的全路径
                    string[] path = Directory.GetDirectories(@"C:UsersSpringRainDesktop
    ew");
                    for (int i = 0; i < path.Length; i++)
                    {
                        Console.WriteLine(path[i]);
                    }
                    Console.ReadKey();
    
    
                    //判断指定的文件夹是否存在
                    if (Directory.Exists(@"C:a"))
                    {
                        for (int i = 0; i < 100; i++)
                        {
                            Directory.CreateDirectory(@"C:a" + i);
                        }   
                    }
                    Console.WriteLine("OK");
                    Console.ReadKey();
         //目录属性设置方法:DirectoryInfo.Atttributes
         //下面的代码设置c:	empuploadsNewDirectory目录为只读、隐藏。与文件属性相同,目录属性也是使用FileAttributes来进行设置的。
         DirectoryInfo NewDirInfo = new DirectoryInfo(@"c:	empuploadsNewDirectoty");
         NewDirInfo.Atttributes = FileAttributes.ReadOnly|FileAttributes.Hidden;
    

    CopyDirectory

            public static void CopyDirectory(string srcdir, string desdir)
            {
                string folderName = srcdir.Substring(srcdir.LastIndexOf("\") + 1);
    
                string desfolderdir = desdir;
    
                string[] filenames = Directory.GetFileSystemEntries(srcdir);
    
                foreach (string file in filenames)// 遍历所有的文件和目录
                {
                    if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    {
                        string currentdir = desfolderdir + "\" + file.Substring(file.LastIndexOf("\") + 1);
                        if (!Directory.Exists(currentdir))
                        {
                            Directory.CreateDirectory(currentdir);
                        }
                        CopyDirectory(file, currentdir);
                    }
    
                    else // 否则直接copy文件
                    {
                        string srcfileName = file.Substring(file.LastIndexOf("\") + 1);
                        srcfileName = desfolderdir + "\" + srcfileName;
                        if (!Directory.Exists(desfolderdir))
                        {
                            Directory.CreateDirectory(desfolderdir);
                        }
                        File.Copy(file, srcfileName, true);
                    }
                }//foreach 
            }//function end
    
  • 相关阅读:
    js 获取时间差
    linq 两个list合并处理,并分组
    单例模式 双锁
    2018年的读书清单
    感悟
    asp.net使用Microsoft.mshtml提取网页标题等解析网页
    //利用反射快速给Model实体赋值
    C# url接口调用
    多字段动态查询
    对图片的操作
  • 原文地址:https://www.cnblogs.com/yinguo/p/11473961.html
Copyright © 2011-2022 走看看