在 C# 中打开文件并替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1915632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:48:24  来源:igfitidea点击:

Open a file and replace strings in C#

c#

提问by Gabe

I'm trying to figure out the best way to open an existing file and replace all strings that match a declared string with a new string, save it then close.

我试图找出打开现有文件的最佳方法,并将与声明的字符串匹配的所有字符串替换为新字符串,保存然后关闭。

Suggestions ?

建议?

采纳答案by Matthias

Can be done in one line:

可以在一行中完成:

File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement"));

回答by Daniel Elliott

using System;
using System.IO;
using System.Text.RegularExpressions;

public static void ReplaceInFile(
                      string filePath, string searchText, string replaceText )
{

    var content = string.Empty;
    using (StreamReader reader = new StreamReader( filePath ))
    {
        content = reader.ReadToEnd();
        reader.Close();
    }

    content = Regex.Replace( content, searchText, replaceText );

    using (StreamWriter writer = new StreamWriter( filePath ))
    {
        writer.Write( content );
        writer.Close();
    }
}

回答by ZombieSheep

If you're reading large filesin, and you string for replacement may not appear broken across multiple lines, I'd suggest something like the following...

如果您正在读取大文件,并且您的替换字符串可能不会出现在多行中,我建议您使用以下内容...

private static void ReplaceTextInFile(string originalFile, string outputFile, string searchTerm, string replaceTerm)
{
    string tempLineValue;
    using (FileStream inputStream = File.OpenRead(originalFile) )
    {
        using (StreamReader inputReader = new StreamReader(inputStream))
        {
            using (StreamWriter outputWriter = File.AppendText(outputFile))
            {
                while(null != (tempLineValue = inputReader.ReadLine()))
                {
                    outputWriter.WriteLine(tempLineValue.Replace(searchTerm,replaceTerm));
                }
            }
        }
    }
}

Then you'd have to remove the original file, and rename the new one to the original name, but that's trivial - as is adding some basic error checking into the method.

然后您必须删除原始文件,并将新文件重命名为原始名称,但这很简单 - 就像在方法中添加一些基本错误检查一样。

Of course, if your replacement text could be across two or more lines, you'd have to do a little more work, but I'll leave that to you to figure out. :)

当然,如果您的替换文本可能跨越两行或更多行,则您需要做更多的工作,但我会将其留给您自己解决。:)

回答by Neo

Slight improvement on the accepted answer that doesn't require Regex, and which meets the requirements of the question:

对不需要正则表达式且满足问题要求的已接受答案略有改进:

File.WriteAllText("Path", File.ReadAllText("Path").Replace("SearchString", "Replacement"));

回答by nnn

public partial class ReadAndChange : System.Web.UI.Page
{
    ArrayList FolderList = new ArrayList();
    ArrayList FolderListSearch = new ArrayList();
    ArrayList FileList = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        AllFolderList("D:\BinodBackup\Nilesh\14.5.2013\Source");
        foreach (string Path in FolderList)
        {
            AllFileList(Path);
        }
        foreach (string Path in FileList)
        {
            ReplaceFile(Path, Path.Replace("Source", "EditedCode"));
        }

        //string SourcePath = "D:\BinodBackup\Nilesh\14.5.2013\Onesource\Onesource\UserManagement\UserControls\AddUserDetails.ascx.cs";
        //string ReplacePath = "D:\AddUserDetails.ascx.cs";
        //ReplaceFile(SourcePath, ReplacePath);
    }

    private static void ReplaceFile(string SourcePath, string ReplacePath)
    {
        int counter = 1;
        string line;

        // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader(SourcePath);
        while ((line = file.ReadLine()) != null)
        {
            if (!(line.Contains("//")))
            {
                if (line.Contains(".LogException("))
                {
                    //Console.WriteLine(counter.ToString() + ": " + line);
                    string[] arr = line.Split(',');
                    string stringToReplace = arr[0].Replace("LogException", "Publish") + " , " + arr[2].Trim() + " , " + arr[3].Replace(");", "").Trim() + " , " + arr[1].Trim() + ");";
                    //File.WriteAllText(currentPath, Regex.Replace(File.ReadAllText(currentPath), line, line + " Added"));
                    File.WriteAllText(ReplacePath, File.ReadAllText(ReplacePath).Replace(line, stringToReplace));
                    //ReplaceInFile(currentPath, line, stringToReplace);
                }
            }

            counter++;
        }

        file.Close();
    }
    private void AllFileList(string FolderPath)
    {
        DirectoryInfo dir = new DirectoryInfo(FolderPath);
        DirectoryInfo[] subdir = dir.GetDirectories();
        if (subdir.Length > 0)
        {

            foreach (DirectoryInfo dr in subdir)
            {
                FileInfo[] files1 = dr.GetFiles();
                foreach (FileInfo file in files1)
                {
                    if(file.Name.EndsWith(".cs"))
                    CheckAndAdd((file.DirectoryName + "\" + file.Name), FileList);
                }

            }
        }
    }

    private void AllFolderList(string FolderPath)
    {
        string CurFolderPatgh = FolderPath;
        Again:
        AddToArrayList(CurFolderPatgh);
        DirectoryInfo dir = new DirectoryInfo(CurFolderPatgh);
        DirectoryInfo[] subdir = dir.GetDirectories();

        if (subdir.Length > 0)
        {
            foreach (DirectoryInfo dr in subdir)
            {
                AddToArrayList(((System.IO.FileSystemInfo)(dir)).FullName + "\" + dr.Name);
            }
        }
        if (FolderListSearch.Count > 0)
        {
            foreach (string dr in FolderListSearch)
            {
                CurFolderPatgh = dr;
                FolderListSearch.Remove(dr);
                goto Again;
            }
        }
    }

    private void AddToArrayList(string FolderPath)
    {
        if (!(FolderList.Contains(FolderPath)))
        {
            CheckAndAdd(FolderPath, FolderList);
            CheckAndAdd(FolderPath, FolderListSearch);
        }
    }

    private void CheckAndAdd(string FolderPath,ArrayList ar)
    {
        if (!(ar.Contains(FolderPath)))
        {
            ar.Add(FolderPath);
        }
    }

    public static void ReplaceInFile(
                      string filePath, string searchText, string replaceText)
    {

        var content = string.Empty;
        using (StreamReader reader = new StreamReader(filePath))
        {
            content = reader.ReadToEnd();
            reader.Close();
        }

        content = content.Replace(searchText, replaceText);

        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.Write(content);
            writer.Close();
        }
    }
}

回答by sinanguler

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;

namespace DevExpressFileEditing
{
    class Program
    {
        static List<FileInfo> _files;
        private static Dictionary<string, string> _replaceList;

        static void Main()
        {
            _files = new List<FileInfo>();
            _replaceList = new Dictionary<string, string>();

            Console.WriteLine("Dark directory searching");
            SearchFilesInDirectories(new DirectoryInfo(@"C:\Sourcebank\Dark"));

            Console.WriteLine("Light directory searching");
            SearchFilesInDirectories(new DirectoryInfo(@"C:\Sourcebank\Light"));

            Console.WriteLine("{0} files found", _files.Count.ToString(CultureInfo.InvariantCulture));

            Console.WriteLine("Replace dictinary creating");
            CreateReplaceList();
            Console.WriteLine("{0} item added", _replaceList.Count.ToString(CultureInfo.InvariantCulture));

            Console.Write("Replacement doing");
            for (int i = 0; i < _files.Count; i++)
            {
                var fileInfo = _files[i];
                Console.CursorLeft = 0;
                Console.Write("{0} of {1}", i.ToString(CultureInfo.InvariantCulture), _files.Count.ToString(CultureInfo.InvariantCulture));
                ReplaceInFile(fileInfo.FullName);
            }
            Console.CursorLeft = 0;
            Console.Write("Replacement done");
        }

        private static void SearchFilesInDirectories(DirectoryInfo dir)
        {
            if (!dir.Exists) return;

            foreach (DirectoryInfo subDirInfo in dir.GetDirectories())
                SearchFilesInDirectories(subDirInfo);

            foreach (var fileInfo in dir.GetFiles())
                _files.Add(fileInfo);
        }

        private static void CreateReplaceList()
        {
            _replaceList.Add("Color=\"#FFF78A09\"", "Color=\"{DynamicResource AccentColor}\"");
            _replaceList.Add("Color=\"{StaticResource ColorHot}\"", "Color=\"{DynamicResource AccentColor}\"");
            _replaceList.Add("Color=\"#FFCC0000\"", "Color=\"{DynamicResource AccentColor}\"");
            _replaceList.Add("To=\"#FFCC0000\"", "To=\"{DynamicResource AccentColor}\"");
            _replaceList.Add("To=\"#FFF78A09\"", "To=\"{DynamicResource AccentColor}\"");
            _replaceList.Add("Background=\"#FFF78A09\"", "Background=\"{DynamicResource Accent}\"");
            _replaceList.Add("Foreground=\"#FFF78A09\"", "Foreground=\"{DynamicResource Accent}\"");
            _replaceList.Add("BorderBrush=\"#FFF78A09\"", "BorderBrush=\"{DynamicResource Accent}\"");
            _replaceList.Add("Value=\"#FFF78A09\"", "Value=\"{DynamicResource Accent}\"");
            _replaceList.Add("Fill=\"#FFF78A09\"", "Fill=\"{DynamicResource Accent}\"");
        }

        public static void ReplaceInFile(string filePath)
        {
            string content;
            using (var reader = new StreamReader(filePath))
            {
                content = reader.ReadToEnd();
                reader.Close();
            }

            content = _replaceList.Aggregate(content, (current, item) => current.Replace(item.Key, item.Value));

            using (var writer = new StreamWriter(filePath))
            {
                writer.Write(content);
                writer.Close();
            }
        }
    }
}