我如何搜索一个文本文件的单词和替换它在C#? [英] How can I search a text file for word and replace it in C#?

查看:114
本文介绍了我如何搜索一个文本文件的单词和替换它在C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个看起来像这样的文本文件:

I created a text file that looks somewhat like this:

Hello <name>! You and <name> will go for a run in the <place>.

我想用用户输入替换文件中的名称变量,并允许重复。例如,名称可能会出现两次,并且应该能够接受不同的答案。

I want to replace the name variables in the file with user input and allow for repeats. For instance name may appear twice and should be able to take in different answers.

Console.Write("Enter a name: ");
Console.Write("Enter another name: ")

文件和括号,但我不知道如何去做这个。

I realize I have to search the file and the brackets, but I'm not sure how to go about doing this. Any advice is appreciated.

推荐答案

使用 File.ReadAllText()获取文件的内容,替换它们并将其保存回如下:

Use File.ReadAllText() to get the contents of the file, replace them and save it back like this:

string contents = File.ReadAllText("somefile.txt"); //Change this to your file.
contents = contents.Replace("<name>", nameVariable).Replace("<place>", placeVariable);
File.WriteAllText("somefile.txt", contents);

您需要导入 System.IO 命名空间。

这篇关于我如何搜索一个文本文件的单词和替换它在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆