We help IT Professionals succeed at work.

How to delete between specific lines from text file in C#

Hakan
Hakan asked
on
Hello,

I've one text file and i'd like to delete lines between two specific lines then i'd like to add new lines between these two lines. I really need an expert support for correct approach how to do that.

Any help would be great! and thanks.

Start string:

ifctngroup.begin (                  $G_mnt_nlin                   )                           ! $G_mnt_nlin

Open in new window


End String:

ifctngroup.end (                    $G_mnt_nlin                   )                           ! $G_mnt_nlin

Open in new window


SampleData
Comment
Watch Question

KimputerIT Manager
CERTIFIED EXPERT

Commented:
If there will be 5 lines deleted, do you mean to replace it with ONE new line each time, or the same (in this case, 5) empty lines?
Are you sure this file contains only spaces? Not tabs?

Bill PrewTest your restores, not your backups...
CERTIFIED EXPERT
Expert of the Year 2019
Top Expert 2016

Commented:
I'm assuming you have some skills in C# since you are asking in that group.

Conceptually this feels fairly straight forward.

- open the input file for reading
- open the output file for writing
- read each line from input file, and write it to output file until you hit the "start" text match
- write the new lines you want to insert to output file
- continue reading the input file looking for the "end" text match, not writing them anywhere
- once you see the "end" text match, go back to reading lines from input and writing them to output

There are several ways you can implement this, setting a flag once you see "start" or "end", or a mode switch etc, or just moving on to different sections of logic and looping, that's often a personal preference.


»bp
Microsoft Dynamics CRM Consultant
CERTIFIED EXPERT
Commented:
Hi,

Try below code-

            string startString = "ifctngroup.begin (                  $G_mnt_nlin                   )                           ! $G_mnt_nlin";
            string endString = "ifctngroup.end (                    $G_mnt_nlin                   )                           ! $G_mnt_nlin";
            int start = s.LastIndexOf(startString) + startString.Length;
            int end = s.IndexOf(endString, start);
            string result = s.Remove(start, end - start);

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.