Home > Blockchain >  I need to replace a line with particular string with contents of another file using c#
I need to replace a line with particular string with contents of another file using c#

Time:03-07

I have two files , File1.txt and File2.txt , I need to replace a particular string in file1 with contents of file2 using C# console application.

file 1 :

This is a sample file

..

code-block ..

some text

end of file

File 2 :

// some c# code //

i need to replace the string "code-block" with the contents of File 2.

Edit 1:

I had tried to read the file as Array and also as a list

var fileContent = File.ReadAllLines(file_path);
            List<string> allLinesText = File.ReadAllLines(file_path).ToList();
            string parentdirectory = Directory.GetParent(Path.GetDirectoryName(file_path)).FullName.ToString(); 

            foreach( var line in fileContent)
            {

                if ( line.Contains("{% code-block %}"))
                {
                    string code_path = line.Replace("{%", string.Empty).Replace("%}", string.Empty).Trim();
                    string code_fullpath = Path.Combine(parentdirectory, code_path);
                    if(File.Exists(code_fullpath))
                    {
                        var code_content = File.ReadAllLines(code_fullpath);
                       // int insert_code_at = 

                     // allLinesText.Insert( allLinesText.IndexOf(line)
                    }
                    
                }

CodePudding user response:

string[] f1 = File.ReadAllLines("f1.txt");
string f2 = File.ReadAllText("f2.txt");
string replaceString = "text";

f1[Array.IndexOf(f1, replaceString)] = f2;

What about this? Reads the first file line by lines, reads the second with all its text and replace the line in the first file to the second file content by getting the index of the replace text in f1

CodePudding user response:

You can use String.Replace. Sample code:

string text = File.ReadAllText("file1.txt");
text = text.Replace("text needs to be replaced", "new text");
File.WriteAllText("file1.txt", text);
  • Related