如何在文本文件中获取字符串的行并使用C#进行更改

huangapple go评论52阅读模式
英文:

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);
}

huangapple
  • 本文由 发表于 2023年2月19日 17:32:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499167.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定