'I need to replace a line with particular string with contents of another file using c#
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)
}
}
Solution 1:[1]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tafsir Ahamed |
