tags:

views:

131

answers:

1

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.

+1  A: 

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);
             }
         }
    }
}
ArsenMkrt
I tried but it still doesn't work. The same error as in my code occurs during debugging:"The process cannot access the file 'C:\abc\2ap-15.mol' because it is being used by another process."And it stops on the following line:"File.AppendAllText(fileName, "M END" + Environment.NewLine);"
Alex
Oh, yea, I didn't note , try edited code now
ArsenMkrt