c#2.0开发的一个文本字符串替换工具,控制台工具,可以批量替换

本文介绍了一个命令行工具,用于在多种场景下动态更改软件配置文件中的特定字符串,支持文件名通配符匹配及选项参数,包括是否区分大小写、使用正则表达式、交换文件或系统环境变量等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

namespace replace
{
    class Program
    {
        static void Main(string[] args)
        {

            if (args.Length == 0||(args.Length == 1 && (args[0] == "/?" || args[0] == "?" || args[0] == "-?")))
            {
                Console.WriteLine("replace 命令行工具");
                Console.WriteLine("作者:zj53hao@qq.com");
                Console.WriteLine("优快云:http://blog.youkuaiyun.com/zj53hao");
                Console.WriteLine("用途:在很多需要动态更改某些软件的配置文件时非常有用");
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("replace 命令运用语法阐明");
                Console.WriteLine("  replace [/?|?|-?]    显示帮助信息");
                Console.WriteLine("  replace [path/]filename search replace [/option]  交换文本文件中的字符串,支持通配符文件名");
                Console.WriteLine("  replace setname search replace [/option]  交换参数变量中的字符串");
                Console.WriteLine("/option参数阐明:");
                Console.WriteLine("   i 区分大小写.  默许不区分");
                Console.WriteLine("   r 运用正则表达式查找文本。留空则运用纯文本交换");
                Console.WriteLine("   f 交换文件 默许");
                Console.WriteLine("   v 交换的是系统环境变量.和f不能同时出现");
                Console.WriteLine();
                Console.WriteLine("如: replace *.txt 查找字符串 交换字符串");
                Console.WriteLine("如: replace setname 查找字符串 交换字符串");
                Console.WriteLine("如: replace myinc/*.txt 查找字符串 交换字符串 /i");
                Console.WriteLine("如: replace setname 查找字符串 交换字符串 /irv");
            }

            if (args.Length == 3)
            {
                ReplaceFiles(args[0],args[1],args[2],null);
            }


            if (args.Length == 4)
            {
                if (args[3].Contains("v"))
                {
                    ReplaceVariable(args[0], args[1], args[2], args[3]);
                }

                else
                {
                    ReplaceFiles(args[0], args[1], args[2], args[3]);
                }

            }


        }


        /// 
        /// 交换环境变量中某个变量的文本值。可以是系统变量,用户变量,临时变量。交换时会覆盖原始值。小心运用
        /// 
        /// 
        /// 
        /// 
        /// 

        public static void ReplaceVariable(string variable, string search, string replace, string options)
        {
            string text=Environment.GetEnvironmentVariable(variable);
            System.Windows.Forms.MessageBox.Show(text);
            text=ReplaceText(text, search, replace, options);
            Environment.SetEnvironmentVariable(variable, text);
            text = Environment.GetEnvironmentVariable(variable);
            System.Windows.Forms.MessageBox.Show(text);
        }




        /// 
        /// 批量交换文件文本
        /// 
        /// 

        public static void ReplaceFiles(string path,string search, string replace, string options)
        {
            
            string[] fs;
            if(File.Exists(path)){
                ReplaceFile(path, search, replace, options);
                return;
            }

            if (Directory.Exists(path))
            {
                fs = Directory.GetFiles(path);
                foreach (string f in fs)
                {

                    ReplaceFile(f, search, replace, options);
                }

                return;
            }


            int i=path.LastIndexOf("/");
            if(i<0)i=path.LastIndexOf("/");
            string d, searchfile;
            if (i > -1)
            {
                d = path.Substring(0, i + 1);
                searchfile = path.Substring(d.Length);
            }

            else
            {
                d = System.Environment.CurrentDirectory;
                searchfile = path;
            }


            searchfile = searchfile.Replace(".", @".");
            searchfile = searchfile.Replace("?", @"[^.]?");
            searchfile = searchfile.Replace("*", @"[^.]*");
            //System.Windows.Forms.MessageBox.Show(d);  System.Windows.Forms.MessageBox.Show(searchfile);
            if (!Directory.Exists(d)) return;
            fs = Directory.GetFiles(d);
            foreach (string f in fs)
            {
                if(System.Text.RegularExpressions.Regex.IsMatch(f,searchfile))
                    ReplaceFile(f, search, replace, options);
            }

        }

        
        /// 
        /// 交换单个文本文件中的文本
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 

        public static bool ReplaceFile(string filename, string search, string replace,string options)
        {
            FileStream fs = File.OpenRead(filename);
            

            //判别文件是文本文件还二进制文件。该方法似乎不科学
            byte b;
            for (long i = 0; i < fs.Length; i++)
            {
                b = (byte)fs.ReadByte();
                if (b == 0)
                {
                    System.Windows.Forms.MessageBox.Show("非文本文件");
                    return false;//有此字节则表示改文件不是文本文件。就不必交换了
                }

            }


            //判别文本文件编码规则。
            byte[] bytes = new byte[2];
            Encoding coding=Encoding.Default;
            if (fs.Read(bytes, 0, 2) > 2)
            {
                if (bytes == new byte[2] { 0xFF, 0xFE }) coding = Encoding.Unicode;
                if (bytes == new byte[2] { 0xFE, 0xFF }) coding = Encoding.BigEndianUnicode;
                if (bytes == new byte[2] { 0xEF, 0xBB }) coding = Encoding.UTF8;
            }


            fs.Close();

            //交换数据
            string text=File.ReadAllText(filename, coding);
            text=ReplaceText(text,search, replace, options);
            File.WriteAllText(filename, text, coding);
            return true;
        }



        /// 
        /// 交换文本
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 

        public static string ReplaceText(string text, string search, string replace, string options)
        {

            RegexOptions ops = RegexOptions.None;
            if (options == null)  //纯文本交换
            {
                search = search.Replace(".", @".");
                search = search.Replace("?", @"?");
                search = search.Replace("*", @"*");
                search = search.Replace("(", @"(");
                search = search.Replace(")", @")");
                search = search.Replace("[", @"[");
                search = search.Replace("[", @"[");
                search = search.Replace("[", @"[");
                search = search.Replace("{", @"{");
                search = search.Replace("}", @"}");
                ops |= RegexOptions.IgnoreCase;
            }

            else
            {
                if(options.Contains("I"))ops |= RegexOptions.IgnoreCase;
            }


            text = Regex.Replace(text, search, replace, ops);
            return text;
        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值