英文:
How to get the line of a string in a text file and change it with C#
问题
我想找出字符串在文本文件中的位置,然后用另一个字符串替换该行。
var location = "bla bla bla";
string fileContents = File.ReadAllText(location);
if (fileContents.Contains("LastSession\tcallsign"))
{
// 在这里,我想将“LastSession\tcallsign”的行信息保存到一个字符串变量中,然后用另一个字符串替换它
}
英文:
I want to find out the line of where the string exist in the text file and then change the line with another string
var location = "bla bla bla";
string fileContents = File.ReadAllText(location);
if (fileContents.Contains("LastSession\tcallsign"))
{
// here i want to save the line info of the "LastSession\tcallsing into a string variable then replace the string with another string
}
答案1
得分: 1
你可以使用以下代码:
StringComparison comparison = StringComparison.Ordinal; // 如果需要,更改为OrdinalIgnoreCase
string searchString = "LastSession\tcallsign";
string replaceString = "new value";
var newLines = File.ReadLines(location)
.Select(GetNewLineInfo)
.Select(x => x);
// 如果需要知道行号
var matchLineNumbers = newLines.Where(x => x.Contains).Select(x => x.LineNumber);
// 如果需要使用新行重写文件:
File.WriteAllLines(location, newLines.Select(x => x.NewLine));
(bool Contains, string NewLine, int LineNumber) GetNewLineInfo(string line, int index)
{
bool contains = line.IndexOf(searchString, comparison) >= 0;
return (contains, contains ? line.Replace(searchString, replaceString) : line, index + 1);
}
英文:
You could use:
StringComparison comparison = StringComparison.Ordinal; // change to OrdinalIgnoreCase if desired
string searchString = "LastSession\tcallsign";
string replaceString = "new value";
var newLines = File.ReadLines(location)
.Select(GetNewLineInfo)
.Select(x => x);
// if you want to know the line-numbers
var matchLineNumbers = newLines.Where(x => x.Contains).Select(x => x.LineNumber);
// if you want to rewrite the file with the new lines:
File.WriteAllLines(location, newLines.Select(x => x.NewLine));
(bool Contains, string NewLine, int LineNumber) GetNewLineInfo(string line, int index)
{
bool contains = line.IndexOf(searchString, comparison) >= 0;
return (contains, contains ? line.Replace(searchString, replaceString) : line, index + 1);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论