C#读取记事本内容并创建新的记事本

来源:互联网 发布:网络推广服务合同书 编辑:程序博客网 时间:2024/05/19 03:16

    晚上写了个小工具,提取txt中整型和浮点型数据,废话不多说,直接上代码。

 //验证浮点型
        public bool fudian(string fudian)
        {
            if (string.IsNullOrEmpty(fudian))
                return false;
            return System.Text.RegularExpressions.Regex.IsMatch(fudian, @"^(-?\d+)(\.\d+)?$");
        }
        //验证整型
        public bool zhengxing(string zhengxing)
        {
            if (string.IsNullOrEmpty(zhengxing))
                return false;
            return System.Text.RegularExpressions.Regex.IsMatch(zhengxing, @"^-?\d+$");
        }

       int count = 0;

       string Matchlast = null;

 private void button1_Click(object sender, EventArgs e)
        {

          try{
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "打开文本文档";
                openFileDialog.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                //打开多个文件
                openFileDialog.Multiselect = true;
                openFileDialog.ShowDialog();
                if (openFileDialog.FileNames.Length <= 0)
                {
                    MessageBox.Show("请选择要转换的文件!");
                    return;
                }
                //count为选中的文件数量
                count = openFileDialog.FileNames.Length;

                //foreach实现逐个读取、输出文件
                foreach (string s in openFileDialog.FileNames)
                {

                     //s为文本路径

                      string filePath = s;

                    //读取文件

                    StreamReader read = new StreamReader(filePath, Encoding.GetEncoding("gb2312"));//filePath为文本文件的位置
                    //创建文件
                    StreamWriter write = new StreamWriter(filePath, false, Encoding.GetEncoding("gb2312"));//注意:filePath为保存的路径

                    string FileText = read.ReadToEnd();

                    string[] s1 = FileText.Split(':', ',', ' ', '\n');//分割注意分割数据的时候当数字在一行的最后位置时候会带一个"回车",刚刚测试了半天才发现
                    for (int j = 0; j < s1.LongLength; j++)
                    {

                        //验证浮点型和整型数据
                        bool result = fudian(s1[j].Trim());
                        bool result1 = zhengxing(s1[j].Trim());
                        if (result || result1)
                        {


                            Matchlast += s1[j].ToString() + ",";


                        }
                    }

                     write.WriteLine(Matchlast );

                    write.Close();
                    read.Close();

                 }

                  MessageBox.Show("成功转换"+count+"条数据");

           }

           catch(Exception ex)

            {

                 MessageBox.Show("转换错误,错误原因为"+ex.ToString());

             }

   }

原创粉丝点击