开发者

How to append text to multiple files

I am not a programmer, but I am a researcher and I need to modify some files. I have a number of text files with *.mol extension located in c:\abc\ directory . I need to append line containing f开发者_如何学运维ollowing text "M END" to each file in this list. I tried following in C# but without any result:

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 the solution.

Thank You!


Would you be satisfied with this oneliner that you can put in any DOS batch (.bat) file:

FOR %%I IN (c:\abc\*.mol) DO ECHO M  END>>%%I


foreach (string fileName in Directory.GetFiles("directory", "*.mol"))
{
    File.AppendAllText(fileName, Environment.NewLine + "M  END");
}


You'll need to loop through all the files matching that pattern and write to them individually. The StreamWriter constructor you're using only supports writing to an individual file (source).

You can get a list of files using:

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


You need to iterate over the files in the directory. DirectoryInfo / FileInfo makes it easy to do this. Also, since you want to append to the end, you need to seek the stream before writing your signature at the end.

Here's a solution that works solely at that location. You will need to add recursive support to descend into subdirectories if desired.

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);
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜