I have a Console File, I need to match a string ("Seq Started"), And if I get the string I want to copy all text till I get another string("Seq Ended") in a txt file.
Asked
Active
Viewed 246 times
2 Answers
0
You can use this.
We load the file and parse lines to search the starting and ending deliminers sequences assuming only one of each of them are allowed.
Then if the section is correclty found, we extract the lines of the soure using Linq and we save the result to the desired file.
using System.Linq;
using System.Collections.Generic;
static void Test()
{
string delimiterStart = "Seq Started";
string delimiterEnd = "Seq Ended";
string filenameSource = "c:\\sample source.txt";
string filenameDest = "c:\\sample dest.txt";
var result = new List<string>();
var lines = File.ReadAllLines(filenameSource);
int indexStart = -1;
int indexEnd = -1;
for ( int index = 0; index < lines.Length; index++ )
{
if ( lines[index].Contains(delimiterStart) )
if ( indexStart == -1 )
indexStart = index + 1;
else
{
Console.WriteLine($"Only one \"{delimiterStart}\" is allowed in file {filenameSource}.");
indexStart = -1;
break;
}
if ( lines[index].Contains(delimiterEnd) )
{
indexEnd = index;
break;
}
}
if ( indexStart != -1 && indexEnd != -1 )
{
result.AddRange(lines.Skip(indexStart).Take(indexEnd - indexStart));
File.WriteAllLines(filenameDest, result);
Console.WriteLine($"Content of file \"{filenameSource}\" extracted to file {filenameDest}.");
}
else
{
if ( indexStart == -1 )
Console.WriteLine($"\"{delimiterStart}\" not found in file {filenameSource}.");
if ( indexEnd == -1 )
Console.WriteLine($"\"{delimiterEnd}\" not found in file {filenameSource}.");
}
}
-
There can be multiple "Seq start". I want the first "Seq start" and continue till the "Seq End" does not come.Can you help me in this? I am new to c#. – Shubham Agrawal Oct 03 '19 at 04:42
-1
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");
// Display the file contents by using a foreach loop.
System.Console.WriteLine("Contents of WriteLines2.txt = ");
foreach (string line in lines)
{
if(line == "Seq Started" && line != "Seq Ended")
{
//here you get each line in start to end one by one.
//apply your logic here.
}
}
Check the second example in below link- [https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-from-a-text-file][1]

Shilpa
- 164
- 1
- 9