返回顶部

收藏

目录内文件批量查找替换字符串内容

更多

C#目录内文件批量查找替换字符串内容

ReplaceText.cs

using System;
using System.Collections.Generic;

using System.Text;
using System.Text.RegularExpressions;
using System.IO;
public class MyClass
{
    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;
    }
    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