1. 程式人生 > >C#讀取檔案內容,在指定行插入內容

C#讀取檔案內容,在指定行插入內容

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        public string txtFilePath = null;
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.Title = "請選擇檔案";
            //fileDialog.Filter = "檔案(*.txt,*.cs)|*.txt;*.cs";
            fileDialog.Filter = "檔案(*.txt)|*.txt";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName.Substring(fileDialog.FileName.LastIndexOf('\\') + 1);
                //textBox1.Text = file;
                //Regex regex = new Regex("[^\\]+(..+)$");
                //Match result = regex.Match(file);
                //if (result.Success) {
                   // textBox1.Text = result.Value;
                //}
                textBox1.Text = file;
                txtFilePath = fileDialog.FileName;
            }
        }

        List<String> txtList = new List<String>();
        private void button2_Click(object sender, EventArgs e)
        {
            if (!File.Exists(txtFilePath))
            {
                MessageBox.Show("file not exist!");
                return;
            }
            FileStream fs = new FileStream(txtFilePath, FileMode.Open);
            
            using (StreamReader sr = new StreamReader(fs, Encoding.Default)) {
                //List<String> list = new List<String>();
                //String input;
                while(!sr.EndOfStream){
                    String s = sr.ReadLine().ToString();
                    String c = null;
                    if (s.IndexOf("NVARCHAR2")>=0)
                    {
                       int a =int.Parse(s.Substring(s.IndexOf("(") + 1, s.IndexOf(")")-s.IndexOf("(")-1));
                       String b = s.Replace("NVARCHAR2","[StringLength("+a+", ErrorMessage = \"請輸入"+a+"個字元\")]");
                       c = b.Remove(b.LastIndexOf("("),b.LastIndexOf(")")-b.LastIndexOf("(")+2);
                       //Console.WriteLine(c);
                    }
                    if (s.IndexOf("NUMBER") >= 0) {
                        int d = s.IndexOf(")") - s.IndexOf("(") - 1;
                        if (d >= 0)
                        {
                            String a = s.Substring(s.IndexOf("(") + 1, d);
                            if (a.Contains(","))
                            {
                                String b = s.Replace("NUMBER", "[RegularExpression(RegexPatterns.NONEGATIVE_NUMERIC, ErrorMessage = \"該資訊必須是數字\")]");
                                c = b.Remove(b.LastIndexOf("("), b.LastIndexOf(")") - b.LastIndexOf("(") + 2);
                                //Console.WriteLine(c);
                            }
                            else
                            {
                                String b = s.Replace("NUMBER", "[RegularExpression(RegexPatterns.NONEGATIVE_INTEGER, ErrorMessage = \"該資訊必須是整數\")]");
                                c = b.Remove(b.LastIndexOf("("), b.LastIndexOf(")") - b.LastIndexOf("(") + 2);
                                //Console.WriteLine(c);
                            }
                        }
                        else {
                            c = s;
                        }                                            
                    }
                    txtList.Add(c);                    
                }
                Console.WriteLine(txtList.ToString());
            }
            
        }

        String csFilePath = null;
        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.Title = "請選擇檔案";
            //fileDialog.Filter = "檔案(*.txt,*.cs)|*.txt;*.cs";
            fileDialog.Filter = "檔案(*.cs)|*.cs";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                string file = fileDialog.FileName.Substring(fileDialog.FileName.LastIndexOf('\\') + 1);
                //textBox1.Text = file;
                //Regex regex = new Regex("[^\\]+(..+)$");
                //Match result = regex.Match(file);
                //if (result.Success) {
                // textBox1.Text = result.Value;
                //}
                textBox2.Text = file;
                csFilePath = fileDialog.FileName;
            }
        }

        List<String> csList = new List<string>();
        private void button5_Click(object sender, EventArgs e)
        {
            if (!File.Exists(csFilePath))
            {
                MessageBox.Show("file not exist!");
                return;
            }
            FileStream fs = new FileStream(csFilePath, FileMode.Open);

            using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
            {
                //List<String> list = new List<String>();
                //String input;
                while (!sr.EndOfStream)
                {
                    csList.Add(sr.ReadLine().ToString());

                }
                Console.WriteLine(txtList.ToString());
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            // 利用SaveFileDialog,讓使用者指定檔案的路徑名
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "CS檔案|*.cs";
            if (saveDlg.ShowDialog() == DialogResult.OK) {
                FileStream fs = File.Open(saveDlg.FileName, FileMode.Create, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                for (int i = 0; i < csList.Count; i++)
                {
                    //開始寫入
                    sw.WriteLine(csList[i]);
                    if (csList[i].Contains("[Column"))
                    {
                        String field = csList[i].Replace("[Column(\"", "").Replace("\")]", "").ToLower().Trim();
                        for (int j = 0; j < txtList.Count; j++)
                        {
                            if (txtList[j] != null)
                            {
                                String sSub = txtList[j].Substring(0, txtList[j].IndexOf("[")).Trim();
                                if (sSub == field)
                                {
                                    String sWrite = txtList[j].Substring(txtList[j].IndexOf("["));
                                    sw.WriteLine(sWrite);
                                }
                            }
                        }
                    }

                }
                //清空緩衝區
                sw.Flush();
                //關閉流
                sw.Close();
                fs.Close();
            }           
        }
}