简体   繁体   中英

How to write a line only once in a text file

I have two text files bala.txt and bala1.txt

bala.txt contains text line by line as

balamurugan,rajendran,chendurpandian
christopher
updateba

bala1.txt contains text line by line as

 ba

Here i need to check bala1.txt with bala.txt and write into a log file as

Pattern Name:ba
LineNo : 1 : balamurugan,rajendran,chendurpandian
LineNo : 3 : updateba

now its writing like this

 Pattern Name :ba
LineNo : 1 : balamurugan,rajendran,chendurpandian
LineNo : 2 : christopher
Pattern Name :ba
LineNo : 3 : updateba

Here is my code

while ((line = file.ReadLine()) != null)
                                    {
              if (line.IndexOf(line2,StringComparison.CurrentCultureIgnoreCase) != -1)
                    dest.WriteLine("Pattern Name :" + line2);
                    dest.WriteLine("LineNo : " + counter.ToString() + " : " + line);
                                        counter++;
                                    }
                                    file.BaseStream.Seek(0, SeekOrigin.Begin);
                                        //(0, SeekOrigin.Begin);
                                    counter = 1;

I dont know how to write pattern name ba only once...Any suggestion??

To do the least amount of change to your code, you can change it like this:

        bool patternwritten = false;
        while ((line = file.ReadLine()) != null)
                                {
          if (line.IndexOf(line2,StringComparison.CurrentCultureIgnoreCase) != -1)
                if( !patternwritten){
                  dest.WriteLine("Pattern Name :" + line2);
                  patternwritten = true;
                }
                dest.WriteLine("LineNo : " + counter.ToString() + " : " + line);
                                    counter++;
                                }
                                file.BaseStream.Seek(0, SeekOrigin.Begin);
                                    //(0, SeekOrigin.Begin);
                                counter = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM