0

Good morning! I have a text file that looks like this:

enter image description here

I want to make the text file look like this from my script:

enter image description here

My idea was to delete every "sign" from the right to the " | " so that only the username remains. Or removing everything from the left, from the first " | ". I only don't know how to code that. Im thankful for any help! If something's unclear, feel free to ask! :)

File text:

Jeff|14|0||4/7/2020 9:22:15 AM|0

Tom123|8|0||4/7/2020 10:47:36 AM|1

  • 1
    Don't you have any example code about what have you tried before? Just to give you a more acqurate answer. – David Apr 08 '20 at 07:58
  • open old file, create new file , read line, split by pipe, write first element(of split result) to new file, repeat(reading) until end of old file ... where is the problem? – Selvin Apr 08 '20 at 07:59
  • @Selvin , i don't know the code :) –  Apr 08 '20 at 08:06

2 Answers2

1
 var someString = "Jeff|blah|foo|bar";
 var justJeff = someString.Substring(0, someString.IndexOf('|'));
Zer0
  • 7,191
  • 1
  • 20
  • 34
0

Simple solution would be to use File.ReadAllLines() to gather the lines from the file into a string[], then File.WriteAllLines() to write the lines back to the file. We can split each line on '|' using string.Split(), then get the first item using Enumerable.Select() from LINQ. MSDN has some good documentation on how to read text files.

using System.IO;
using System.Linq;

// other code

var path = "C:\\file.txt";

var lines = File.ReadAllLines(path).Select(line => line.Split('|')[0]);

File.WriteAllLines(path, lines);

If you dealing with big files, it might be better to use File.ReadLines(), which reads one line at a time. This is different to File.ReadAllLines(), which reads the whole file into memory at once. You can have a look at What is the difference between File.ReadLines() and File.ReadAllLines()? for more information.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75