Hi all,
I am new to c#. I am trying to read a text and find a string from that text file. I want to get the text between two particular line number . Intially i want to get two particular string's line number . then the text between these two strings needs to be copied to a new file.
I have not progressed a lot on this. Here is what i have till now

string filePath = @"d:\file.txt";
            StreamReader streamReader = new StreamReader(filePath);
            string text = streamReader.ReadToEnd();
           
            streamReader.Close();

            string regMatch = "Active Routes:";//string to search for inside of text file. It is case sensitive.
            if (Regex.IsMatch(text, regMatch))//If the match is found in allRead
            {
                Console.WriteLine("found\n");
               
              

            }
            else
            {
                Console.WriteLine("not found\n");
            }

First i want the line number of the matching text.

Recommended Answers

All 24 Replies

How about (I use a dictionary but you could use any container to keep track of the line numbers or strings):
(you can flesh out the other portions -- I can't have all the fun)

bool found = false,last = false; 
                //strdict is of type <int,string>
                while ((temp = sr.ReadLine()) != null)
                {
                    if (Regex.IsMatch(temp, regMatch))
                    {
                        if (found)
                            last = true;
                        
                        found = !found;
                     }

                    if (found ||last)
                    {
                        strdict[lineNumber] = temp;
                    }

                    if (last)
                        break;
                    
                    lineNumber++;
                }

This gets the lines starting with the first match and up to the second match (I think that's what you were trying to do...).

thanks for the reply. I am trying to achieve what you have told.
I am new to this c# . that has caused me the problem in strdict.. What is the header to be used to use this code :(

also i tried with

string filePath = @"d:\file.txt";
 StringReader re = new StringReader(filePath);
 string temp = null;
while ((temp = re.ReadLine()) != null)
            {
                if (Regex.IsMatch(temp, regMatch))
                {
                    if (found)
                        last = true;

                    found = !found;
                }

                if (found || last)
                {
                  //  strdict[lineNumber] = temp;
                    Console.WriteLine(lineNumber);
                    Console.ReadLine();
                }

                if (last)
                    break;

                lineNumber++;
            }

but this code is getting d:\file.txt as the value in the while loop and is not reading line by line

This works for me. but i have to work on this to get the desired result

StringReader re = new StringReader(readtext);
           // bool found = false, last = false;                 //strdict is of type <int,string>                while ((temp = sr.ReadLine()) != null)                {                    if (Regex.IsMatch(temp, regMatch))                    {                        if (found)                            last = true;                         found = !found;                     }                     if (found ||last)                    {                        strdict[lineNumber] = temp;                    }                     if (last)                        break;                     lineNumber++;                }                bool found = false,last = false; 
            //strdict is of type <int,string>
            string temp = null;
          //  streamReader.ReadLine();
            while ((temp = re.ReadLine()) != null)
            {
                if (Regex.IsMatch(temp, regMatch))
                {
                    if (found)
                        last = true;

                    found = !found;
                }

                if (found || last)
                {
                  //  strdict[lineNumber] = temp;
                    Console.WriteLine(lineNumber);
                    Console.ReadLine();
                }

                if (last)
                    break;

                lineNumber++;

since i got the line number , i want to copy the text file between these two to a new file . any idea

Dictionary <int,string> strdict = new Dictionary<int,string>();

but this code is getting d:\file.txt as the value in the while loop and is not reading line by line

I'm not sure what you mean by this. Console.ReadLine() reads one line at a time until there are no more lines to read.

since i got the line number , i want to copy the text file between these two to a new file . any idea

use a streamwriter and reverse the process. Use a foreach loop to step through the dictionary. Read briefly on the Dictionary container (google c# dictionary. Write each line out one by one.

Instead of putting Console.ReadLine(); after the last line is read, just put Console.ReadKey() at the very end of your program.

The solution provided by you was too good .
The reading part , i was giving the filename for streamread expecting that the data from the file will be read. Instead i replaced it with the data text itself.

StreamReader streamReader = new StreamReader(filePath);
            string readtext = streamReader.ReadToEnd();
    StringReader re = new StringReader(readtext);
  string temp = null;
        
            while ((temp = re.ReadLine()) != null)
{
.....
}

My current problem is that in the text file obtained, there are numeric values like 257, 266 etc. i want to compare the value and check whether the first one is greater than second one. Is there a way to achieve this>?

You don't need anything after the first line in this snippet. If you read the file to the end then the SR won't have anything more to read.

StreamReader streamReader = new StreamReader(filePath);
            string readtext = streamReader.ReadToEnd();
    StringReader re = new StringReader(readtext);
  string temp = null;

My current problem is that in the text file obtained, there are numeric values like 257, 266 etc. i want to compare the value and check whether the first one is greater than second one. Is there a way to achieve this>?

Where are the values coming from? The line numbers? If they are different numbers you'll have to parse the individual lines for the numbers.

while ((temp = re.ReadLine()) != null)
            {
                if (Regex.IsMatch(temp, regMatch))
                {
                                       found = !found;
                }

                if (found || last)
                {
            

                    // Write the string to a file.

                    if (Regex.IsMatch(temp, "======"))
                        break;

                   System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\test.txt",true);
                                 file.WriteLine(temp);

                  file.Close();

                
                }
}

This is what i am doing in the while part. i am writing a part of the text to a particulart file.
The values in this new file is

192.168.10.255  255.255.255.255         On-link     192.168.10.71    276
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     192.168.10.71    276
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     192.168.10.71    276

I want to compare the values like 276 with 306 etc.

Use

List<string[]> sl = new List<string[]>();
            string temp;
            string [] delim = {" "};
            using (StreamReader sr = new StreamReader("data.txt"))
            {
                while ((temp = sr.ReadLine()) != null)
                {

                    sl.Add(temp.Split(delim, StringSplitOptions.RemoveEmptyEntries));
                }

                
            }

(this was just my test program so you can do the manipulations on temp directly)
Then use Int32.Parse to get the last element in each string array and compare them however you wish.

a quick problem

System.Diagnostics.Process.Start("cmd.exe", @"/c del  d:\\file.txt"); //Delete the  output dump file

i am trying to delete the file.txt after the use using the dos command. but the file is not getting deleted.

a quick problem

System.Diagnostics.Process.Start("cmd.exe", @"/c del  d:\\file.txt"); //Delete the  output dump file

i am trying to delete the file.txt after the use using the dos command. but the file is not getting deleted.

Did you close the streamwriter with the Close() method? Theoretically the "using" statement should take care of that, but it's probably a good habit to explicitly close it. I didn't close my streamreader in one of the other posts, it was an oversight.

Use

List<string[]> sl = new List<string[]>();
            string temp;
            string [] delim = {" "};
            using (StreamReader sr = new StreamReader("data.txt"))
            {
                while ((temp = sr.ReadLine()) != null)
                {

                    sl.Add(temp.Split(delim, StringSplitOptions.RemoveEmptyEntries));
                }

                
            }

(this was just my test program so you can do the manipulations on temp directly)
Then use Int32.Parse to get the last element in each string array and compare them however you wish.

due to my lack of knowledge,I tried to use

Int32 testvalue = 0;
 while ((temp2 = sr.ReadLine()) != null)
                {
                    sl.Add(temp2.Split(delim, StringSplitOptions.RemoveEmptyEntries));
                                 
                }
  testvalue = Int32.Parse(sl(0));

it throw me the error that " sl is a variable ,but is used like a method"
when i debugged the sl variable, my needed data is in sl(0).(0).(4) which holds the value 276

Did you close the streamwriter with the Close() method? Theoretically the "using" statement should take care of that, but it's probably a good habit to explicitly close it. I didn't close my streamreader in one of the other posts, it was an oversight.

Here is my complete code

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            
            string regMatch = "Active Routes:";//string to search for inside of text file. It is case sensitive.

            string filePath = @"d:\file.txt"; 
        
            bool found = false, last = false;

            System.Diagnostics.Process.Start("cmd.exe", @"/c route print > d:\file.txt"); // Get the route print to text file
            StreamReader streamReader = new StreamReader(filePath);
            string readtext = streamReader.ReadToEnd();
            streamReader.Close();
       
            if (Regex.IsMatch(readtext, regMatch))//If the match is found in allRead
            {
                Console.WriteLine("found\n");

            }
            else
            {
                Console.WriteLine("not found\n");
            }
 Console.ReadLine();

  



            /* delete all unwanted files */
            System.Diagnostics.Process.Start("cmd.exe", @"/c del  d:\\file.txt"); //Delete the  output dump file
            System.Diagnostics.Process.Start("cmd.exe", @"/c del  d:\\madavas1.txt"); // delete madavas1.txt
            System.Diagnostics.Process.Start("cmd.exe", @"/c del  d:\\madavas2.txt"); // delete madavas2.txt

            System.IO.StreamWriter file1 = new System.IO.StreamWriter("d:\\madavas1.txt"); // Create fresh madavas1.txt
            file1.Close();
            
            System.IO.StreamWriter file2 = new System.IO.StreamWriter("d:\\madavas2.txt"); // Create fresh madavas2.txt
            file2.Close();

/* create mdavas2.txt for active route*/
            
            StringReader madvas2 = new StringReader(readtext);
                string madvas2temp = null;

                while ((madvas2temp = madvas2.ReadLine()) != null)
            {
                if (Regex.IsMatch(madvas2temp, regMatch))
                {
                   

                    found = !found;
                }

                if (found || last)
                {

                    if (Regex.IsMatch(madvas2temp, "======"))
                    {
                        found = false;
                        break;
                    }

                    System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\madavas2.txt", true);

                    file.WriteLine(madvas2temp);

                  file.Close();

                                }
            }
                madvas2.Close();
                /* create mdavas1.txt for persistent route*/

                StringReader madvas1 = new StringReader(readtext);
                string madvas1temp = null;
                regMatch = "Persistent Routes:";
                while ((madvas1temp = madvas1.ReadLine()) != null)
                {
                    if (Regex.IsMatch(madvas1temp, regMatch))
                    {
                                              found = !found;
                    }

                    if (found || last)
                    {

                        if (Regex.IsMatch(madvas1temp, "======"))
                        {
                            found = false;
                            break;
                        }

                        System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\madavas1.txt", true);

                        file.WriteLine(madvas1temp);

                        file.Close();


                    }
                }
                madvas1.Close();


                List<string[]> sl = new List<string[]>();

                string temp2; 
            string[] delim = { " " };
            Int32 testvalue = 0;
            using (StreamReader sr = new StreamReader("d:\\madavas2.txt"))
            {
                while ((temp2 = sr.ReadLine()) != null)
                {
                    sl.Add(temp2.Split(delim, StringSplitOptions.RemoveEmptyEntries));
                                
                }
                     }

        //    Console.ReadKey();
        }

    }
}

i have closed it

You index a list by [] just like an array. sl[0] gets you the first array of strings and sl[0][4] gets you the last entry in the first array of strings.

It's best with any kind of stream operation to use the using keyword, as it disposes of the resources properly. Try in lines 15-17 to have it follow the

using (StreamReader sr = new StreamReader(file))
{
       lines 16-17

} //closing this off destroys the object

EDIT: StringReader madvas2 = new StringReader(readtext); on line 47 is wrong, readtext is your text string, not a path.

It's best with any kind of stream operation to use the using keyword, as it disposes of the resources properly. Try in lines 15-17 to have it follow the

using (StreamReader sr = new StreamReader(file))
{
       lines 16-17

} //closing this off destroys the object

EDIT: StringReader madvas2 = new StringReader(readtext); on line 47 is wrong, readtext is your text string, not a path.

Yes Readtext is the text string. My understanding is that we have to give the text and not the path. when i gave the path , it was taking the path as complete string and i was not getting the proper output

Yes Readtext is the text string. My understanding is that we have to give the text and not the path. when i gave the path , it was taking the path as complete string and i was not getting the proper output

i am facing a problem at the starting itself

 string regMatch = "Active Routes:";//string to search for inside of text file. It is case sensitive.

            string filePath =@"d:\file.txt";
            string readtext = "";
                     System.Diagnostics.Process.Start("cmd.exe", @"/c route print > d:\file.txt"); // Get the route print to text file
            [B]using (StreamReader streamReader = File.OpenText([COLOR="Red"]filePath[/COLOR][/B]))
            {

                string s = "";
                if ((s = streamReader.ReadLine()) != null)
                {
                    readtext = streamReader.ReadToEnd();                   
                }
            }
probelm is in the highlighted part.[code]Could not find file 'd:\file.txt'.[/code]
Here is my complete code. 
[code]
class Program
    {
        static void deletefiles()
        {

            System.IO.File.Delete("d:\\madavas1.txt");// delete madavas1.txt
            System.IO.File.Delete("d:\\madavas2.txt");// delete madavas2.txt
            System.IO.File.Delete("d:\\file.txt"); //Delete the  output dump file
        }

        static void Main(string[] args)
        {
            string regMatch = "Active Routes:";//string to search for inside of text file. It is case sensitive.
               string filePath = @"d:\file.txt";
            string readtext = "";
            string path = "";
            bool found = false, last = false;

            path = @"d:\\file.txt";
            if (!File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path)) // Create a file to write to madavas2.txt.
                {
                }
            }
            System.Diagnostics.Process.Start("cmd.exe", @"/c route print > d:\file.txt"); // Get the route print to text file
            using (StreamReader streamReader = File.OpenText(filePath))
            {
                    string s = "";
                if ((s = streamReader.ReadLine()) != null)
                {
                    readtext = streamReader.ReadToEnd();// streamReader.ReadToEnd();

                }
            }

            /* delete all unwanted files */
            deletefiles();

            path = @"d:\\madavas1.txt";
            if (!File.Exists(path))
            {
                // Create a file to write to madavas1.txt.
                using (StreamWriter sw = File.CreateText(path))
                {
                }
            }
            path = @"d:\\madavas2.txt";
            if (!File.Exists(path))
            {
                // Create a file to write to madavas2.txt.
                using (StreamWriter sw = File.CreateText(path))
                {
                }
            }

              /* create mdavas2.txt for active route*/

            StringReader madvas2 = new StringReader(readtext);
            string madvas2temp = null;

            while ((madvas2temp = madvas2.ReadLine()) != null)
            {
                if (Regex.IsMatch(madvas2temp, regMatch))
                {
                    found = !found;
                }
                if (found)
                {
                    if (Regex.IsMatch(madvas2temp, "======"))
                    {
                        found = false;
                        break;
                    }
                    System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\madavas2.txt", true);
                    file.WriteLine(madvas2temp);
                    file.Close();
                }
            }
            madvas2.Close();
            /* create mdavas1.txt for persistent route*/
             StringReader madvas1 = new StringReader(readtext);
            string madvas1temp = null;
            regMatch = "Persistent Routes:";
            while ((madvas1temp = madvas1.ReadLine()) != null)
            {
                if (Regex.IsMatch(madvas1temp, regMatch))
                {
                    found = !found;
                }
                if (found || last)
                {
                    if (Regex.IsMatch(madvas1temp, "======"))
                    {
                        found = false;
                        break;
                    }
                    System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\madavas1.txt", true);
                    file.WriteLine(madvas1temp);
                    file.Close();
                }
            }
            madvas1.Close();
            List<string[]> sl = new List<string[]>();
             string temp2;
            string[] delim = { " " };
            Int32 testvalue = 0;
            using (StreamReader sr = new StreamReader("d:\\madavas2.txt"))
            {
                while ((temp2 = sr.ReadLine()) != null)
                {
                    sl.Add(temp2.Split(delim, StringSplitOptions.RemoveEmptyEntries));
                    // testvalue=int32.parse(s1(0));
                }
                testvalue = Int32.Parse(sl[2][4]);
            }
            deletefiles();
        }
       }

EDIT: StringReader madvas2 = new StringReader(readtext); on line 47 is wrong, readtext is your text string, not a path.

Is completely incorrect on my part. I misunderstood what you were trying to do. I'll work on the other part and get back to you.

if (!File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path)) // Create a file to write to madavas2.txt.
                {
                }
            }

I'd let the command prompt worry about creating the actual file. If I remember correctly the redirect > simply clobbers whatever file it was anyway. You should test for it after the file has supposedly been created, though, it couldn't hurt.

same thing with this part

path = @"d:\\madavas1.txt";
            if (!File.Exists(path))
            {
                // Create a file to write to madavas1.txt.
                using (StreamWriter sw = File.CreateText(path))
                {
                }
            }
            path = @"d:\\madavas2.txt";
            if (!File.Exists(path))
            {
                // Create a file to write to madavas2.txt.
                using (StreamWriter sw = File.CreateText(path))
                {
                }
            }

In the regex stuff, the way I had it toggling the found (found = !found) it will miss the last line that matches the regex pattern. That's why I had put that (found || last) portion in.

There are a couple of stringreaders and I think one streamwriter that should have using statements also.

Otherwise, if possible could you put up a sample madras1 and madras2 (as text) and probably a file.txt (I can run route print on my machine but the results may be different). Obfuscate them all you want, in fact throw in some artificial regex matches to see if it works.

This program you can run in your PC.
It will run a route print commnad and get the result to file.txt.
in route print , there are two parts. first is active route and next is persistant route. My aim is to get these two seperated into two different files madvas1.txt and madvas2.txt. ie , it will be a subset of the file.txt. There a lot more calulcation to be done with the values, which you can ignore from the list string part

I KNOW THIS CODE IS NOT THE BEST, THERE ARE A LOT OF MISTAKES :(

You may want to obfuscate your MAC number in the file.txt I think you should be ok behind a router but I'm not up on the nefarious side of things.

EDIT: path = @"d:\\file.txt"; should either be a literal string (with the @) or with the escaped backslash, not both. Same with the rest of the paths (some need @ and don't have them and have single slashes). So pick one style and stick with it.

You may want to obfuscate your MAC number in the file.txt I think you should be ok behind a router but I'm not up on the nefarious side of things.

The project is to modify these values; So no options for me other than playing with these :(

path = @"d:\\file.txt"; should either be a literal string (with the @) or with the escaped backslash, not both.

this was causing me a lot of problem :) , Thanks a lot

I just meant to change a digit here and there but ok. See my edit to the above post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.