How to add text to multiple files

I am not a programmer, but I am a researcher, and I need to change some files. I have several text files with the * .mol ​​extension located in the c: \ abc \ directory. I need to add a line containing the following text "M END" for each file in this list. I tried following in C #, but without any results:

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

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = new StreamWriter("c:\\abc\\*.mol", true); 
            sw.WriteLine("M  END"); 
            sw.Close();   

        }
    }
}

Please suggest a solution.

Thanks!

+3
source share
4 answers

You would be happy with this oneliner, which you can put in any DOS package (.bat):

FOR %%I IN (c:\abc\*.mol) DO ECHO M  END>>%%I
+7
source
foreach (string fileName in Directory.GetFiles("directory", "*.mol"))
{
    File.AppendAllText(fileName, Environment.NewLine + "M  END");
}
+3
source

, , . StreamWriter, , ().

, :

 string[] filePaths = Directory.GetFiles("c:\\abc\\", "*.mol");
+1

You need to iterate over the files in the directory. DirectoryInfo / FileInfo simplifies this. Also, since you want to add an end, you need to look for the stream before writing your signature at the end.

Here is a solution that works exclusively in this place. You will need to add recursive support to descend into subdirectories, if necessary.

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

namespace appender
{
    class Program
    {
        static void AppendToFile(FileInfo fi)
        {
            if (!fi.Exists) { return; }

            using (Stream stm = fi.OpenWrite())
            {
                stm.Seek(0, SeekOrigin.End);

                using (StreamWriter output = new StreamWriter(stm))
                {
                    output.WriteLine("M  END");
                    output.Close();
                }
            }
        }

        static void Main(string[] args)
        {
            DirectoryInfo di = new DirectoryInfo("C:\\abc\\");
            FileInfo[] fiItems = di.GetFiles("*.mol");

            foreach (FileInfo fi in fiItems)
            {
                AppendToFile(fi);
            }
        }
    }
}
+1
source

Source: https://habr.com/ru/post/1719623/


All Articles