C#基础代码段

文件路径

 class MyPath
    {
        public static string GetFileName(string path)
        {
            int lastIndex = path.LastIndexOf("\\");
            return path.Substring(lastIndex + 1);
        }
        public static string GetExtension(string path)
        {
            int lastIndex = path.LastIndexOf(".");
            return path.Substring(lastIndex + 1);
        }
        public static string GetFileNameWithoutExtension(string path)
        {
            int index1 = path.LastIndexOf("\\");
            int index2 = path.LastIndexOf(".");
            return path.Substring(index1 + 1, index2 - index1 - 1);
        }
        public static string GetDirectory(string path)
        {
            int index = path.LastIndexOf("\\");
            return path.Substring(0, index);
        }
    }

    class Program
    {
        #region  
        //static void Main(string[] args)
        //{
        //    Console.WriteLine("请输入文件名");
        //    string line = Console.ReadLine();

        //    string name = MyPath.GetDirectory(line);
        //    Console.WriteLine(name);
        //    Console.ReadKey();
        //} 
        #endregion



        static void Main(string[] args)
        {
            // 练习7:“192.168.10.5[port=21,type=ftp]”,这个字符串表示
            // IP地址为192.168.10.5的服务器的21端口提供的是ftp服务,其
            // 中如果“,type=ftp”部分被省略,则默认为http服务。请用程序解
            // 析此字符串,然后打印出“IP地址为***的服务器的***端口提供的
            // 服务为***” line.Contains(“type=”)。192.168.10.5[port=21]

            string s1 = "192.168.10.5[port=21,type=ftp]";
            string s2 = "192.168.10.5[port=21]";

            string s3 = "202.123.234.111[port=34567,database=127.0.0.1,domain=www.jk.jk.jk]";

            // 首先是IP
            string[] temps = s3.Split("[]".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            // [0]  IP
            // [1]  键值对

            string ip = temps[0];
            
            // 
            string[] subTemps = temps[1].Split(',');
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < subTemps.Length; i++)
            {
                // 获得端口号与服务类型
                string[] ss = subTemps[i].Split('=');
                // [0]  名字
                // [1]  值
                dic.Add(ss[0], ss[1]);
            }
            // 是否存在type,如果存在就表示有提供,否则表示默认的http,需要手动提供
            if (!dic.ContainsKey("type"))
            {
                dic.Add("type", "http");
            }

            // 打印出结果
            Console.WriteLine("IP:" + ip);
            foreach (KeyValuePair<string, string> item in dic)
            {
                Console.WriteLine("{0}:{1}", item.Key, item.Value);
            }
            Console.ReadKey();
        }
    }

读取文件

class Program
    {
        static void Main(string[] args)
        {
            string[] lines = File.ReadAllLines("salary.txt", Encoding.Default);
            double dMin, dMax, dAvg;
            double sum = 0;
            double num = Convert.ToDouble(lines[0].Split(':')[1]);
            dMax = num;
            dMin = num;
            sum = num;

            for (int i = 1; i < lines.Length; i++)
            {
                num = Convert.ToDouble(lines[i].Split(':')[1]);
                if (dMin > num)
                {
                    dMin = num;
                }
                if (dMax < num)
                {
                    dMax = num;
                }
                sum += num;
            }

            dAvg = sum / lines.Length;

            Console.WriteLine("最大值是:{0}", dMax);
            Console.WriteLine("最小值是:{0}", dMin);
            Console.WriteLine("平均值是:{0}", dAvg);
            Console.ReadKey();
        }
    }

集合

 class Program
    {
        static void Main(string[] args)
        {
            Exercise6();

        }


        static void Exercise1()
        {
            // IEnumerable
            // IEnumerable<T>
            // 可枚举
            List<string> list1 = new List<string>("a,b,c,d,e,f,g".Split(','));
            List<string> list2 = new List<string>(new string[] { "f", "g", "h", "i", "j", "k" });

            // 遍历一个集合,将这个集合中,不在另一个结合中的项加入进去
            //for (int i = 0; i < list2.Count; i++)
            //{
            //    if (!list1.Contains(list2[i]))
            //    {
            //        list1.Add(list2[i]);
            //    }
            //}


            // HashSet<T>的泛型集合
            // 唯一的集合
            list1.AddRange(list2);

            HashSet<string> h = new HashSet<string>(list1);

            // h.ToArray(

            (123).GetHashCode();
        }


        static void Exercise2()
        { 
            // 随机数
            Random r = new Random();
            // r.Next()         创建一般的随机数
            // r.Next(int)      创建0到该数字的随机数,该数字取不到
            // r.Next(int, int) 创建制定数字范围的随机数,左边取得到,右边取不到

            List<int> list = new List<int>();
            while (list.Count < 10)
            { 
                int num = r.Next(1, 101);
                // 限制条件
                if (!list.Contains(num) && num % 2 == 0)
                {
                    list.Add(num);
                }
            }


            // 创建一个由0-9组成的一个随机数,要去数字长度为10并且每一个数字都不重复
            // 随机创建一个字母,填充到一个长度为10的数组中要求所有的字母不重复
        }

        // 创建一个由0-9组成的一个随机数,要求数字长度为10并且每一个数字都不重复
        // 随机创建一个字母,填充到一个长度为10的数组中要求所有的字母不重复
        static void Exercise2_1()
        {
            List<string> list = new List<string>();
            Random r = new Random();
            while(list.Count<10)
            {
                string n = r.Next(10).ToString();
                if (!list.Contains(n))
                {
                    list.Add(n);
                }
            }
            // 判断第一个是否为0

            Console.WriteLine(string.Join("", list));
            Console.ReadKey();
        }

        static void Exercise2_2()
        {
            //char c = (char)97;
            //Console.WriteLine(c);
            //Console.ReadKey();



            //char[] cs = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); // { 'a', 'b', 'c', ... };
            //List<char> list = new List<char>();
            //Random r = new Random();
            //while (list.Count < 10)
            //{
            //    int n = r.Next(26);
            //    char c = cs[n];
            //    if (!list.Contains(c))
            //    {
            //        list.Add(c);
            //    }
            //}


            // 节约空间
            List<char> list = new List<char>();
            Random r = new Random();
            while (list.Count < 10)
            {
                int n = r.Next(26 * 2); // 包含大小写字母
                // char c = (char)('a' + n);
                //char c;
                //if (n > 25)
                //{
                //    // 大写字母
                //    c = (char)('A' + (n - 26));
                //}
                //else
                //{ 
                //    // 小写字母
                //    c = (char)('a' + n);
                //}

                char c = (char)(n > 25 ? ('A' + (n - 26)) : ('a' + n));

                if (!list.Contains(c))
                {
                    list.Add(c);
                }
            }
            Console.WriteLine(string.Concat(list));
            Console.ReadKey();
        }

        static void Exercise3()
        {
            string s = "1 33 2 55 4 6 8 7"; // 1 3 5 7 2 4 6 8;
            List<string> listOdd = new List<string>(); // odd 是奇数
            List<string> listEven = new List<string>(); // even 偶数
            string[] ss = s.Split(' ');
            for (int i = 0; i < ss.Length; i++)
            {
                // 判断奇偶
                string temp = ss[i]; // 数字的字符串 "1"
                char lastNumChar = temp[temp.Length - 1]; // 结尾的数字字符   '1' 49
                int lastNum = lastNumChar - '0';  // '1' - '0'   => 49 - 48 = 1

                //if (lastNum % 2 == 0)
                //{
                //    // temp是偶数
                //    listEven.Add(temp);
                //}
                //else
                //{ 
                //    // 是奇数
                //    listOdd.Add(temp);
                //}

                switch (lastNum)
                { 
                    case 0:
                    case 2:
                    case 4:
                    case 6:
                    case 8: listEven.Add(temp); break;
                    default: listOdd.Add(temp); break;
                }
            }
        }

        static void Exercise4()
        {
            // char[] chs = "零一二三四五六七八九".ToCharArray();
            string str = "1壹 2贰 3叁 4肆 5伍 6陆 7柒 8捌 9玖 0零";
            Dictionary<char, char> dic = new Dictionary<char, char>();
            string[] temps = str.Split(' ');
            for (int i = 0; i < temps.Length; i++)
            {
                string num = temps[i];
                dic.Add(num[0], num[1]);
            }

            Console.WriteLine("请输入");
            char[] input = Console.ReadLine().ToCharArray();

            for (int i = 0; i < input.Length; i++)
            {
                if (dic.ContainsKey(input[i]))
                {
                    input[i] = dic[input[i]];
                }

            }

            Console.WriteLine(new string(input));
            Console.ReadKey();
        }

        static void Exercise5()
        { 
            // 简单的做法:限定要翻译什么,然后具体实现
            // 1-31
            // 找规律
            // 一个数字 1 2 ... 直接翻译
            // 两个数字 
            //      11 12...    前面加十,后面照样翻译
            //      30 20...    前面照样翻译,后面加十
            //      21 31...    照样翻译,中间插入一个十
            /*
            string num = "10";
            if (num.Length == 1)
            {
                // 照样翻译();
            }
            else if (num.Length == 2)
            {
                if (num[0] == '1')
                { 
                
                }
                else if (num[1] == '0')
                {

                }
                else
                { 
                    
                }
            }
            else 
            {
            }
            */



            // 通用做法,翻译任意一个数字
            // 个,十,百,千,万,十万,百万,千万,亿
            // 1,234,567

            // 1        一个
            // 12       一十二个
            // 30       三十零个
            // 31       三十一个

            // 12345
            // 五个
            // 四十
            // 三百
            // 二千
            // 一万
        }


        static void Exercise6()
        {
            Console.WriteLine("请输入一句话");
            string input = Console.ReadLine();

            Dictionary<char, int> dic = new Dictionary<char, int>();

            for (int i = 0; i < input.Length; i++)
            {
                char ch = input[i];
                if (dic.ContainsKey(ch))
                {
                    dic[ch]++;
                }
                else
                {
                    dic.Add(ch, 1);
                }
            }

            foreach (KeyValuePair<char, int> item in dic)
            {
                Console.WriteLine("字符{0},出现{1}次", item.Key, item.Value);
            }

            Console.ReadKey();
        }



    }

分割文件

 class Program
    {
        static void Main(string[] args)
        {
            // 提示用户输入文件名
            // 保存名,一般使用文件名加一个后缀,后缀注意有序号
            // 计算每一个文件要都多少个字节 Math.Ceiling()
            // 利用循环或分步骤写文件
            Console.WriteLine("请输入文件名");
            string file = Console.ReadLine();

            using (FileStream f = new FileStream(file, FileMode.Open, FileAccess.Read))
            { 
                // 创建几个
                int maxsize = (int)Math.Ceiling(f.Length * 1.0 / 2);

                using (FileStream f1 = new FileStream(file + ".1", FileMode.Create, FileAccess.Write))
                {
                    byte[] buffer = new byte[10];
                    int total = 0;
                    int count = 0;
                    while ((count = f.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        f1.Write(buffer, 0, count);
                        total += count;
                        if (total >= maxsize)
                        {
                            break;
                        }

                    }
                }
                using (FileStream f1 = new FileStream(file + ".2", FileMode.Create, FileAccess.Write))
                {
                    byte[] buffer = new byte[10];
                    int total = 0;
                    int count = 0;
                    while ((count = f.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        f1.Write(buffer, 0, count);
                        total += count;
                        if (total >= maxsize)
                        {
                            break;
                        }

                    }
                }
            }
        }
    }

文件名保存

class Program
    {
        static void Main(string[] args)
        {
            //for (int i = 0; i < args.Length; i++)
            //{
            //    Console.WriteLine(args[i]);
            //}

            //Console.ReadKey();


            // 文件名  保存文件名
            /*
            using (要保存的FileStream)
            {
                for (int i = 0; i < 有几个文件; i++)
                {
                    using (读取的文件i)
                    { 
                        将i写到保存的文件中
                    }
                }
            }
            */

            string[] froms = args[0].Split("+".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            string fileSave = args[1];

            using (FileStream file = new FileStream(fileSave, FileMode.Create, FileAccess.Write))
            {
                for (int i = 0; i < froms.Length; i++)
                {
                    // 将i个文件都写到file中
                    using (FileStream temp = new FileStream(froms[i], FileMode.Open, FileAccess.Read))
                    {
                        int count = 0;
                        byte[] bs = new byte[10];
                        while ((count = temp.Read(bs, 0, bs.Length)) > 0)
                        {
                            file.Write(bs, 0, count);
                        }
                    }
                }
            }

            // 打印赋值了多少个文件

        }
    }

文件合并与分割

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            cmbSizeTemp.SelectedIndex = 0;
        }

        private void btnFileName_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtFileName.Text = ofd.FileName;
                }
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            txtSize.Enabled = rbSize.Checked;
        }

        private void rbNum_CheckedChanged(object sender, EventArgs e)
        {
            txtNum.Enabled = rbNum.Checked;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog fbd = new FolderBrowserDialog())
            {
                if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtSave.Text = fbd.SelectedPath;
                }
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            string fileName = txtFileName.Text.Trim();
            string savePath = txtSave.Text.Trim();
            string size = txtSize.Text.Trim();
            string num = txtNum.Text.Trim();

            #region 验证
            if (fileName.Length == 0 || savePath.Length == 0 || rbSize.Checked && size.Length == 0 || rbNum.Checked && num.Length == 0)
            {
                MessageBox.Show("请填写完整信息");
                return;
            }
            if (!File.Exists(fileName))
            {
                MessageBox.Show("该文件不存在");
                return;
            }
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            #endregion

            string fileNameTemp = Path.GetFileName(fileName);

            using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                long fileSize = file.Length;
                // 得到文件分卷的个数
                int countTemp = 0;
                // 根据文件长度计算出分割出的文件大小(字节)
                long sizeTemp = 0;
                if (rbSize.Checked)
                {
                    // 使用指定文件大小
                    if (!long.TryParse(size, out sizeTemp))
                    {
                        MessageBox.Show("输入指定大小不正确,请从新输入...");
                        return;
                    }
                    sizeTemp *= 1024;
                    countTemp = (int)Math.Ceiling(fileSize * 1.0 / sizeTemp);
                }
                else
                {
                    // 使用指定文件个数
                    if (int.TryParse(num, out countTemp))
                    {
                        sizeTemp = (long)(fileSize * 1.0 / countTemp);
                    }
                    else
                    {
                        MessageBox.Show("输入分卷个数有误,请从新输入... ");
                        return;
                    }
                }
                // 得到每个分卷的大小 sizeTemp:long(字节数)
                // 得到文件的个数 countTemp:int
                // MessageBox.Show(sizeTemp + "," + countTemp);
                // 缓存数组
                byte[] bs = new byte[1024 * Convert.ToInt32(cmbSizeTemp.SelectedItem)];
                int current = 0; // 每次读取的字节数
                for (int i = 0; i < countTemp; i++)
                {
                    long countEveryTimes = 0;
                    string fileSaveName = Path.Combine(savePath, fileNameTemp + ".jk" + i.ToString("000"));
                    // MessageBox.Show(fileSaveName);
                    using (FileStream fileSave = new FileStream(fileSaveName, FileMode.Create, FileAccess.Write))
                    {
                        while ((current = file.Read(bs, 0, bs.Length)) > 0)
                        {
                            fileSave.Write(bs, 0, current);
                            countEveryTimes += current;
                            if (countEveryTimes >= sizeTemp)
                            {
                                break;
                            }
                        }
                    }
                }
            }

            MessageBox.Show("分割保存完毕...");
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Multiselect = true;
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    foreach (string item in ofd.FileNames)
                    {
                        lbJoinFiles.Items.Add(new JKFileModel() { FileFullName = item, FileName = Path.GetFileName(item) });
                    }
                }
            }
        }

        private void btnJoin_Click(object sender, EventArgs e)
        {
            // 遍历文件,检测文件是否存在
            List<string> files = new List<string>();
            foreach (JKFileModel item in lbJoinFiles.Items)
            {
                if (!File.Exists(item.FileFullName))
                {
                    MessageBox.Show("选择文件有误... ");
                    return;
                }
                files.Add(item.FileFullName);
            }
            // 排序
            files.Sort((x, y) => Convert.ToInt32(Regex.Match(x, @".+jk(\d+)").Groups[1].Value) - Convert.ToInt32(Regex.Match(y, @".+jk(\d+)").Groups[1].Value));
            // 合并
            string fileName = Regex.Replace(files[0], @".jk000", "");
            using (FileStream fileFinal = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                foreach (string item in files)
                {
                    using (FileStream fileTemp = new FileStream(item, FileMode.Open, FileAccess.Read))
                    { 
                        int count = 0;
                        byte[] bs = new byte[1024 * 1024];
                        while ((count = fileTemp.Read(bs, 0, bs.Length)) > 0)
                        {
                            fileFinal.Write(bs, 0, count);
                        }
                    }
                }
            }

            MessageBox.Show("文件合并完毕... ");
        }


    }

class JKFileModel
    {
        public string FileName { get; set; }
        public string FileFullName { get; set; }

        public override string ToString()
        {
            return FileName;
        }
    }

读写流


    class Program
    {
        static void Main(string[] args)
        {
            #region MyRegion
            //using (FileStream file = new FileStream("1.txt", FileMode.Open, FileAccess.Read))
            //{
            //    byte[] buffer = new byte[3];
            //    int count;

            //    count = file.Read(buffer, 0, buffer.Length);
            //    count = file.Read(buffer, 0, buffer.Length);
            //    count = file.Read(buffer, 0, buffer.Length);
            //    count = file.Read(buffer, 0, buffer.Length);
            //} 
            #endregion

            #region MyRegion
            //Random r = new Random();
            //List<int> list = new List<int>();

            //int index = 0;
            //while (list.Count < 10)
            //{
            //    int num = r.Next(10); // 创建0-9的数字
            //    if (!list.Contains(num))
            //    {
            //        if (index != 0 || num != 0)
            //        {
            //            list.Add(num); // 加入表示次数要加一
            //            index++;
            //        }
            //    }
            //}	 
            #endregion


            //Stopwatch sp1 = new Stopwatch();
            //sp1.Start();
            //for (int i = 0; i < 1000; i++)
            //{
            //    File.AppendAllText("1.txt", "1234567890\r\n");
            //}
            //sp1.Stop();
            //Console.WriteLine(sp1.Elapsed);


            //Stopwatch sp2 = new Stopwatch();
            //sp2.Start();
            //using (StreamWriter w = new StreamWriter("2.txt", true, Encoding.UTF8))
            //{
            //    for (int i = 0; i < 1000; i++)
            //    {
            //        w.Write("1234567890\r\n");
            //    }
            //    sp2.Stop();
            //    Console.WriteLine(sp2.Elapsed);
            //}
            Console.ReadKey();
        }
    }

简单记事本

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 打开文件
            using (OpenFileDialog ofd = new OpenFileDialog())
            {

                // DilaogResualt是窗体的返回值
                // MessageBox.Show(
                // ofd.ShowDialog(

                DialogResult res = ofd.ShowDialog();
            
                if (res == System.Windows.Forms.DialogResult.OK)
                {
                    textBox1.Text = File.ReadAllText(ofd.FileName, Encoding.Default);
                }

            }
        }

        private void 保存SToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 将当前文本框中的内容写到文件中 File.WriteAllText

            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                // 默认的后缀名
                sfd.Filter = "文本文件|*.txt";

                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string fileName = sfd.FileName;
                    File.WriteAllText(fileName, textBox1.Text, Encoding.Default);
                }
            }
        }

        private void 修改颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using(ColorDialog cd = new ColorDialog())
            {
                if(cd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    textBox1.ForeColor = cd.Color;
                }
            }
        }

        private void 修改字体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (FontDialog fd = new FontDialog())
            {
                if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    textBox1.Font = fd.Font;
                }
            }
        }
    }

TreeView控件

namespace  TreeView控件
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        int index = 0;
        private void btnAddRootNode_Click(object sender, EventArgs e)
        {
            // 找tvTree的Nodes属性

            //TreeNode tn = tvTree.Nodes.Add("显示的标签文本");

            //tn.Nodes.Add("哈哈,其实很简单");

            tvTree.Nodes.Add("节点" + index++).BackColor = Color.Red;
        }

        private void btnAddSubNode_Click(object sender, EventArgs e)
        {
            // 我选中了谁
            TreeNode tn = tvTree.SelectedNode;
            tn.Nodes.Add("节点" + index++).BackColor = Color.Red;
            

        }

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode tn = tvTree.SelectedNode;
            txtName.Text = tn.Text;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            TreeNode tn = tvTree.SelectedNode;
            tn.Text = txtName.Text;
        }
    }
}

ref与out

class Program
    {
        static void Main(string[] args)
        {
            // TryPase
            //int result;
            //bool isTrue = int.TryParse("123", out result);

            // int num = 10;

            // 将变量nun中存储的值复制一份,赋值给方法
            // Func(ref num);

            Console.Write("Enter User Id:");
            string uid = Console.ReadLine();
            Console.Write("Password:");
            string pwd = Console.ReadLine();
            string msg;
            if (CheckLogin(uid, pwd, out msg))
            {
                Console.WriteLine("欢迎登陆成功");
            }
            else
            {
                Console.WriteLine(msg);
            }

            Console.ReadKey();
        }

        private static void Func(ref int num)
        {
            
        }

        public static bool MyTryParse(string str, out int result)
        {
            // return int.TryParse(str, out result);

            try
            {
                result = Convert.ToInt32(str);
                return true;
            }
            catch
            {
                result = 0;
                return false;
            }


            // 循环遍历看每一个字符位置上是否是数字
        }

        public static bool CheckLogin(string uid, string pwd, out string message)
        { 
            // 假定用户名为admin
            // 密码为888888
            if (uid == "admin" && pwd == "888888")
            {
                message = null;
                return true;
            }
            else if (uid == "admin")
            {
                message = "密码错误";
                return false;
            }
            else
            {
                message = "用户名不存在";
                return false;
            }
        }
    }

使用传统办法创建XML文件

 class Program
    {
        static void Main(string[] args)
        {
            // 命名空间:System.XML;
            // 类库:XmlDocument   文档
            //      XmlElement      元素
            //      XmlAttribute    属性
            XmlDocument xdoc = new XmlDocument();
            // 所有的元素使用文档节点创建
            XmlDeclaration xdec = xdoc.CreateXmlDeclaration("1.0", "gb2312", null);
            xdoc.AppendChild(xdec);

            XmlElement xele = xdoc.CreateElement("root");

            xdoc.AppendChild(xele);

            XmlAttribute xAttr = xdoc.CreateAttribute("id");
            xAttr.Value = "1234567";

            XmlText txt = xdoc.CreateTextNode("我是一个文本节点");

            xele.AppendChild(txt);

            xele.Attributes.Append(xAttr);


            xdoc.Save("1.xml");
        }
    }

使用LinqToXML

 class Program
    {
        static void Main(string[] args)
        {
            // System.XML.Linq; 
            // XDocument
            // XElement
            // XAttribute

            // 兼容做法
            #region 兼容传统的语法
            //XDocument xDoc = new XDocument();
             xDoc.Declaration = new XDeclaration(
             XElement xRoot = new XElement("root", "我是一个文本内容");
            //XElement xRoot = new XElement("root");
            //xRoot.Value = "我是文本";

            //XAttribute xAttr = new XAttribute("Id", "0002");


            //xDoc.Add(xRoot);
            //xRoot.Add(xAttr);


            //xDoc.Save("2.xml"); 
            #endregion


            // 真正Linq的语法
            #region Linq语法演示
            // F#  函数式编程语言
            // 基于函数式
            //new XDocument(
            //        new XElement("root", 
            //                new XAttribute("id", "12345"),
            //                "我是一个根节点"
            //            )
            //    ).Save("3.xml");
            // f1().f2().f3()....
            // 链式编程,流水线生产
            // lisp 
            #endregion

            #region 一个案例
            //string[] strs = "张三,亮亮,马伦,李四(黑皮)".Split(',');
            //Random r = new Random();

            //XDocument xdoc = new XDocument(new XElement("root"));
             xdoc.Root
            //for (int i = 0; i < strs.Length; i++)
            //{
            //    xdoc.Root.Add(new XElement("person",
            //            new XAttribute("id", i+1),
            //            new XAttribute("测试属性", "测试数据"),
            //            new XElement("name", strs[i]),
            //            new XElement("sex", "男女"[r.Next(2)]),
            //            new XElement("age", r.Next(18,65))
            //        ));
            //}

            //xdoc.Save("person.xml"); 
            #endregion

//            XDocument.Parse(@"<?xml version=""1.0"" encoding=""gb2312""?>
//<root>
//    <person id=""123"">测试</person>
//</root>").Save("4.xml");
        }
    }

查找XML

class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Load("person.xml");

            List<XElement> list = new List<XElement>();

            SearchElementsZhao(xdoc.Root, list);

        }


        public static void SearchElementsZhao(XElement ele, List<XElement> list)
        { 
            // 首先遍历ele的所有子节点
            foreach (XElement item in ele.Elements())
            {
                // 判断这个元素的名字是不是name,如果是name看里面存储的是“赵晓虎”
                if (item.Name.LocalName == "name")
                {
                    if (item.Value == "虎")
                    { 
                        // 是我要的
                        list.Add(item.Parent);
                    }
                }

                // 如果item里面还有子节点就递归
                SearchElementsZhao(item, list);
            }
        }
    }

Linq查找

 class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Load("person.xml");

            // 一个是linq查询语法(与sql语句类似),另一个是linq方法语法(Lambda表达式完成查找)
            //var query = from s in xdoc.Descendants()
            //            where s.Name.LocalName == "name" && s.Value == "赵晓虎"
            //            select s.Parent;

            //foreach (XElement item in query)
            //{

            //}


            //foreach (XElement i in xdoc.Descendants().Where(e =>
            //{
            //    if (e.Name.LocalName == "name")
            //    {
            //        if (e.Value == "赵晓虎")
            //        {
            //            return true;
            //        }
            //    }
            //    return false;
            //}))
            //{
            //    XElement obj = i.Parent;
            //}
        }
    }

RSS阅读器

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XDocument rss = XDocument.Load("rss.xml");
            TreeNode tn = treeView1.Nodes.Add("百度新闻");

            LoadData(tn, rss.Root);
        }

        void LoadData(TreeNode tn, XElement ele)
        {
            foreach (XElement ele1 in ele.Elements())
            {
                TreeNode tn1 = tn.Nodes.Add(ele1.Name.ToString());
                if (!ele1.HasElements)
                {
                    tn1.Tag = ele1.Value;
                }
                LoadData(tn1, ele1);
            }

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string html = e.Node.Tag as string;
            if (html != null)
            {
                webBrowser1.DocumentText = html;
            }
        }
    }

违禁词汇

class Program
    {
        static void Main(string[] args)
        {
            string[] lines = File.ReadAllLines("网站过滤词(部分).txt", Encoding.Default);
            // {MOD}  {BANNED}
            List<string> listMod = new List<string>();
            List<string> listBan = new List<string>();
            for (int i = 0; i < lines.Length; i++)
            {
                string[] t = lines[i].Split('='); 
                // [0]词汇   [1]等级
                if (t[1] == "{MOD}")
                {
                    // 成人午夜场
                    // 成.{0,5}人.{0,5}午.{0,5}夜.{0,5}场

                    listMod.Add(string.Join(".{0,5}", t[0].ToCharArray()));
                }
                else
                {
                    listBan.Add(string.Join(".{0,5}", t[0].ToCharArray()));
                }
            }


            while (true)
            {
                Console.WriteLine("请输入您要使用的文本");
                string str = Console.ReadLine();

                // 判断
                // 得到结果
                if (Regex.IsMatch(str, string.Join("|", listBan)))
                {
                    Console.WriteLine("不允许发表");
                }
                else if (Regex.IsMatch(str, string.Join("|", listMod)))
                {
                    Console.WriteLine("待审核发表");
                }
                else
                {
                    Console.WriteLine("可以发表");
                }
            }

        }
    }

下载Email

 class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            wc.Encoding = Encoding.UTF8;
            string html = wc.DownloadString("http://192.168.27.69:8080/大家留下email交友吧_email_天涯社区.htm");
            // 我的邮箱是jk@123.com
            //string regex = @"[a-zA-Z0-9\-\._]+@[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9]+)+";
            // string reges = @"\w+@\w+(\.\w+)+";
            string regex = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            // IsMatch
            // Matches()

            MatchCollection mc = Regex.Matches(html, regex);
            int i = 0;
            foreach (Match m in mc)
            {
                // Match是查询到的结果字符串和其他信息的对象

                // 方法,精细过滤

                Console.WriteLine((i++) + "," +m.Value);
            }
            Console.ReadKey();
        }
    }

提取百家姓

 class Program
    {
        /**
         * 
         * 〔赵〕角音。天水郡。伯益裔孙。造父事周穆王,以功封于赵城,子孙因氏
            焉。其后叔带仕晋,至赵夙世为晋卿;传赵籍,始灭晋为诸侯。汉有赵广汉,为
            京兆尹,宋太祖之远祖。
            〔钱〕徵音。彭城郡。系山篯氏。彭祖姓篯名铿。支子去竹而为钱氏。○篯,
            音尖。铿,音坑。
            〔孙〕宫音。乐安郡。系出姬姓。卫武公子惠孙之孙,以祖字为氏,世为卫
            卿。又楚有孙氏。蒍姓之后。孙叔敖为楚相。又齐有孙氏,陈姓之后,陈无宇子
            子占有功,赐姓孙氏。其后有孙武子。为吴将。武子之裔,世居富春。汉末有孙
            权,为吴帝,武子之裔也。○蒍,音委。
            〔李〕徵音。陇西郡。系出理氏。皋陶之后,代为理官,子孙以官为氏。有
            理利贞避纣居李树下,改为李氏,老子之祖也。其后李牧仕赵,李广仕汉。唐祖
            李渊,广之裔也。又晋有里克,卫有礼至,皆理氏之后,与李同源。
            〔周〕角音。汝南郡。系出姬姓。周平王少子烈之后,以国为氏。周有周任,
            战国有周霄。
         */
        static void Main(string[] args)
        {
            string str = File.ReadAllText("1.txt", Encoding.Default);

            #region 没有使用组
            //MatchCollection mc = Regex.Matches(str, @"〔.+〕");
            //int i = 0;
            //foreach (Match m in mc)
            //{

            //    string s = m.Value.Replace("〔", "").Replace("〕", "");

            //    Console.Write("{0} {1}\t", i++, s);
            //    if (i % 5 == 0)
            //    {
            //        Console.WriteLine();
            //    }

            //} 
            #endregion
            MatchCollection mc = Regex.Matches(str, @"〔(.+)〕");
            int i = 0;
            foreach (Match m in mc)
            {

                string s = m.Groups[1].Value;

                Console.Write("{0} {1}\t", i++, s);
                if (i % 5 == 0)
                {
                    Console.WriteLine();
                }

            }

            Console.ReadKey();
        }
    }

文件名操作

 class Program
    {
        static void Main(string[] args)
        {
            //               12               34   5
            string regex = @"(([a-zA-Z]:).*\\)((.+)(\..+))";

            while (true)
            {
                Console.WriteLine("请输入路径");
                string input = Console.ReadLine();

                Match m = Regex.Match(input, regex);

                Console.WriteLine("根目录为:{0}", m.Groups[2].Value);
                Console.WriteLine("文件路径:{0}", m.Groups[1].Value);
                Console.WriteLine("文件名:{0}", m.Groups[3].Value);
                Console.WriteLine("扩展名:{0}", m.Groups[5].Value);
                Console.WriteLine("没有后缀名的文件名:{0}", m.Groups[4].Value);
                Console.WriteLine("\r\n\r\n");
            }
        }
    }

自定义排序


namespace  自定义排序
{
    // 2
    public delegate int MyCompareHandler(string s1, string s2);

    class Program
    {
        #region MyRegion
        //static void Main(string[] args)
        //{
        //    string[] arr = "100,20,21,120,1,9".Split(',');
        //    // 3
        //    MyCompareHandler cmp;
        //    // 4
        //    // cmp = string.Compare;
        //    // int string.Compare(string s1, string s2)
        //    // s1 > s2   1
        //    // s1 = s2   0
        //    // s1 < s2   -1

        //    cmp = CompareByNum;
        //    // 5
        //    for (int i = 0; i < arr.Length - 1; i++)
        //    {
        //        for (int j = 0; j < arr.Length - i - 1; j++)
        //        {
        //            if (cmp(arr[j], arr[j + 1]) > 0)
        //            {
        //                string t = arr[j];
        //                arr[j] = arr[j + 1];
        //                arr[j + 1] = t;
        //            }
        //        }
        //    }
        //}

        #endregion

        static void Main(string[] args)
        {
            string[] arr = "100,20,21,120,1,9".Split(',');

            // MySort(arr, CompareByNum);
            // MySort(arr, string.Compare);

            // Lambda表达式,简化操作
            // MySort(arr, (a, b) => a.Length - b.Length);
            MySort(arr, (a, b) => Convert.ToInt32(b) -  Convert.ToInt32(a));
        }


        // 1
        public static int CompareByNum(string n1, string n2)
        {
            return Convert.ToInt32(n1) - Convert.ToInt32(n2);
        }
        // string.Compare()



        public static void MySort(string[] arr, MyCompareHandler cmp)
        {
            for (int i = 0; i < arr.Length - 1; i++)
            {
                for (int j = 0; j < arr.Length - i - 1; j++)
                {
                    if (cmp(arr[j], arr[j + 1]) > 0)
                    {
                        string t = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = t;
                    }
                }
            }
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人海中的海盗

你的打赏将是对我的激励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值