天天看點

C# winform修改檔案特定行内容

問題:

    檔案config.bat下有如下内容:

SET EAS_HOME=D:\Kingdee\client\eas

SET JAVA_HOME=D:\Kingdee\client\eas\clientjdk

SET UPDATE_SERVER=180.168.109.70:6886

SET EAS_SERVER=tcp://180.168.109.70:11035

SET JVM_INITIAL_HEAPSIZE=64

SET JVM_MAX_HEAPSIZE=256

SET ONDEMAND_UPDATE=false

SET ISSTART_LOADER=false

SET ISMULTI_LOADER=false

SET ENABLE_CDN=false

對于上述每一行 “=” 号後的内容使用winform窗體 Textbox進行展示,供使用者修改。現在問題是修改後如何儲存到原來的檔案裡。

解決方案:

      在winform中設定Text,及讀取,寫入按鈕,代碼如下:

      private void BtnRead_Click(object sender, EventArgs e)

        {

            try

            {

                StreamReader sr = File.OpenText("D:\\config.bat");

                if (!sr.EndOfStream)

                {

                    string str = sr.ReadLine();

                    string[] zStr = str.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);

                    if (zStr.Length == 2)

                    {

                        if (zStr[0] == "SET EAS_HOME")

                        {

                            textBox1.Text = zStr[1];

                        }

                    }

                }

            }

            catch

            {

            }

        }

        private void BtnWrite_Click(object sender, EventArgs e)

        {

            try

            {

                string[] lines = File.ReadAllLines("D:\\config.bat");

                for (int i = 0; i < lines.Length; i++)

                {

                    string[] zStr = lines[i].Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);

                    if (zStr.Length == 2)

                    {

                        if (zStr[0] == "SET EAS_HOME")

                        {

                            lines[i] = "SET EAS_HOME=" + textBox1.Text;

                        }

                    }

                }

                File.WriteAllLines("D:\\config.bat", lines);          

            }

            catch

            { }

        }

注意:有不同意見者,請在評論時,貼出代碼,以友善大家學習。謝謝。