Alex
Alex

Reputation: 31

How to read certain text containing line and then append this text to those of multiple files in which this text line is absent?

I have multiple files with *.mol extensions. In the last line in some of them there is "M END" text. I need a program reading all these files, searching for "M END" line in that files and write this "M END" to those of them which have not "M END" line at the end of file. I wrote the following C# code, but it doesn't work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {   
            foreach (string fileName in Directory.GetFiles("C:\\abc\\", "*.mol")) 
            {

                System.IO.StreamReader file = new System.IO.StreamReader(fileName);                       
                if ((file.ReadLine()) != ("M  END"))
                {
                    File.AppendAllText(fileName, "M  END" + Environment.NewLine);

                }


            }

        }
    }
}

Please, help me! Thanks for all answers.

Upvotes: 0

Views: 307

Answers (1)

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50722

If your files are not big you can try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (string fileName in Directory.GetFiles("C:\\abc\\", "*.mol"))
            {
               bool shouldAddMEnd = false;
               using (System.IO.StreamReader sw = new System.IO.StreamReader(fileName))
               {
                   shouldAddMEnd = !sw.ReadToEnd().EndsWith("M  END");                        
               } 
               if (shouldAddMEnd)
                   File.AppendAllText(fileName, "M  END" + Environment.NewLine);
             }
         }
    }
}

Upvotes: 1

Related Questions