Tomas Nordström
Tomas Nordström

Reputation: 87

C# Delete line i text file if it is different than specific term

I am editing a textfile and changing content from one value to another. Everything works fine so far but I have reached a dead end when it comes to deleting a line i that file. I want a function that reads a file with similar content as below...

Name Peter

Length 185

Name Susan

Length

Name Harry

Length 177

and removes all lines with the word Length NOT followed by anything and gives the result

Name Peter

Length 185

Name Susan

Name Harry

Length 177

I have used the code

System.IO.File.WriteAllLines(
   strLabelExportTotal,
   File.ReadAllLines(strLabelExportPreLenAdjust)
      .Select(1 => 1 == "LENGTH " ? "LENGTH 0" : 1));

to set that if a value after the word Length is missing it should ad the value 0. But now I want the line to disappear...

Upvotes: 0

Views: 994

Answers (3)

Paritosh
Paritosh

Reputation: 11568

You can use below steps:

  1. Read all text as string
  2. Split lines into strings: \n as splitter
  3. Remove unwanted string/line LENGTH
  4. Combine the remaining list and write the file

Code:

string fileText = File.ReadAllText(path);            
var list = fileText.Split('\n').ToList();
list.Remove("LENGTH");
File.WriteAllLines(path, list);

OR

var list = File.ReadAllLines(path).ToList();
list.Remove("LENGTH");
File.WriteAllLines(path, list);

Upvotes: 1

Trevor
Trevor

Reputation: 1271

You are getting all the lines as an enumerable of lines, and currently you are outputting exactly the same number of lines to the output. The .Select() method won't change the number of items being processed.

You probably want to change the .Select() method to a .Where() method which will only output lines that match a certain predicate.

Something such as:

System.IO.File.WriteAllLines(
   strLabelExportTotal,
   File.ReadAllLines(strLabelExportPreLenAdjust)
      .Where(x => x != "LENGTH "));

Hope this helps

Upvotes: 1

Youssef13
Youssef13

Reputation: 4986

string[] arr = System.IO.File.ReadAllLines(@"C:\file.txt");
string[] arr2 = arr.Cast<string>().Where(line => (line.Trim().ToLower() != "length")).ToArray();
System.IO.File.WriteAllText(@"C:\file.txt", String.Join(Environment.NewLine, arr2);

The first line in code reads the file from path C:\file.txt and have it as an array of string ( each line is an element in this array )

The second line in code process that array and it filters and produce a new array named arr2 where the new array doesn't have any line equals to length.

The third line in code write the new array into the file C:\file.txt

Upvotes: 0

Related Questions