我需要使用 C# 将具有特定字符串的行替换为另一个文件的内容
我有两个文件,File1.txt 和 File2.txt,我需要使用 C# 控制台应用程序将 file1 中的特定字符串替换为 file2 的内容。
文件 1:
这是一个示例文件
..
代码块 ..
文件的一些文本
结尾
文件 2 :
// 一些 c# 代码 //
我需要用文件 2 的内容替换字符串“code-block”。
编辑 1:
我尝试阅读文件既可以是数组,也可以是列表
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)
}
}
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)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
String.Replace
。示例代码:You can use
String.Replace
. Sample code: