stringreplace

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace stringreplace
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                string helpMessage =
         @"Replace string in a file with another string.

STRINGREPLACE [sourcefile] [sourcestring] [targetstring] [targetfile]

Parameter:It have 4 parameter: 
[sourcefile]    Import file name for replace
[sourcestring]  Import source string
[targetstring]  Import replace string
[targetfile]    Export file name";
                Console.WriteLine(helpMessage);
                return;
            }
            string sfile, sstr, tstr, tfile;
            sfile = args[0];
            sstr = args[1];
            tstr = args[2];
            tfile = args[3];

            if (!File.Exists(sfile))
            {
                string errorMessage = string.Empty;
                errorMessage = string.Format("Error:Sourcefile[{0}] is not exist", sfile);
                Console.WriteLine(errorMessage);
                return;
            }

            if (File.Exists(sfile))
            {
                FileStream fs = File.OpenRead(sfile);
                StreamReader sr = new StreamReader(fs);
                string content = sr.ReadToEnd();
                string replacedcontent = content.Replace(sstr, tstr);
                sr.Close();
                fs.Close();

                StreamWriter sw = File.CreateText(tfile);
                sw.Write(replacedcontent);
                sw.Close();
            }
        }
    }
}

發佈了14 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章