C#操作文字檔 在行首和行尾追加文本

來源:互聯網
上載者:User

   起因:

        有七個超過50行的SQL語句。但是不能作為預存程序放在資料庫中。這樣在寫到C#的後台邏輯中需要在每一個行追加SqlStr.Append(“  和 ");這樣兩個東西。

   經過:

       1.在控制台中操作,先將SQL語句複製到VS中,美化一下,將每一行都頂格,也就是保證首字母沒有空格。

       2.將美化好的語句,複製到C:\Test.txt檔案中。並且在同一目錄下建立NewFile.txt檔案,用來存放新檔案。

       3.控制台中寫入以下代碼:

       4.執行,可以看到,在控制台中也顯示了變化後的SQL語句了。然後去NewFile.txt可以去拷貝了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
 
namespace FileOperation {
    class Program {
        static void Main(string[] args) {
            //FileStream fs = new FileStream(@"C:\carError.txt", FileMode.Open, FileAccess.ReadWrite);
            StreamReader objreader = new StreamReader(@"C:\Test.txt",Encoding.Default);
            StreamWriter sw = new StreamWriter(@"C:\NewFile.txt");
            string sline = "";
            ArrayList al = new ArrayList();
            while (sline!=null) {
                sline = objreader.ReadLine();
                if (sline != null) {
                    al.Add("strSql.Append(\" " +sline+"\");");
                }
            }
            objreader.Close();
            foreach (string s in al) {
                sw.WriteLine(s);
                Console.WriteLine(s);
            }
            sw.Close();
            Console.ReadLine();
        }
    }
}

 

    結果:

           1.成功完成追加。注意:在StreamReader中編碼要注意,如果不加編碼,輸出會出現亂碼。

           2.積累。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.