简体   繁体   中英

Replace 1 line in text file Linq c#

I have text file with contain:

ABCD

QWERT

8:20 AM

78910

in the line 3 I want replace to:8:20 AM -> 9:25 AM

try code:

string[] file = File.ReadAllLines(filename);
file = file.Select((x, i) => i > 1 && i < 3 ? x.Replace("8:20 AM", "9:25 AM") : x).ToArray();
File.WriteAllLines(filename, file);

resultz:

ABCD

QWERT

8:20 AM 9:25 AM

78910

can help me replace all text in line 3 of text file. Thanks

The two issues with your code:

  1. You're using Replace , which looks in the string x for "8:20 AM" and replaces that value with "9:25 AM" returning a new string value. You always want the same value to be written to the file, regardless of what's currently on that line in the file. You should therefore return a string literal ( "9:25 AM" ) rather than the result of a replace on x .
  2. Your condition: i > 1 && i < 3 . i is an int (integer) meaning that it only holds whole values. Why don't you simply check i == 2 instead?
string[] file = File.ReadAllLines(filename);
file = file.Select((x, i) => i == 2 ? "9:25 AM" : x).ToArray();
File.WriteAllLines(filename, file);

why using array, you can use list instead it will be much more easier for you.

 string[] file =  File.ReadAllLines(filename);
 var newList = string.Join(" ", file).Split('\n').Select(s => s.Replace("8:20 AM", "9:25 AM")).ToList();

            string output="";
            foreach(var item in newList)
            {
                output += item + "\n";
            }

File.WriteAllLines(filename, output);

Try this. This works, However you have to make sure that the string your getting from textfile is always separated by newline or "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM