如何分割文本文件分割成多个文件?多个、文件分割、文本、文件

2023-09-03 17:21:40 作者:你脸红什么啊

在C#中,什么是最有效的方法来分割文本文件分割成多个文本文件(分割符是一个空行),而preserving的字符编码​​?

In C#, what is the most efficient method to split a text file into multiple text files (the splitting delimiter being a blank line), while preserving the character encoding?

推荐答案

我会使用的StreamReader和StreamWriter类:

I would use the StreamReader and StreamWriter classes:

 public void Split(string inputfile, string outputfilesformat) {
     int i = 0;
     System.IO.StreamWriter outfile = null;
     string line; 

     try {
          using(var infile = new System.IO.StreamReader(inputfile)) {
               while(!infile.EndOfStream){
                   line = infile.ReadLine();
                   if(string.IsNullOrEmpty(line)) {
                       if(outfile != null) {
                           outfile.Dispose();
                           outfile = null;
                       }
                       continue;
                   }
                   if(outfile == null) {
                       outfile = new System.IO.StreamWriter(
                           string.Format(outputfilesformat, i++),
                           false,
                           infile.CurrentEncoding);
                   }
                   outfile.WriteLine(line);
               }

          }
     } finally {
          if(outfile != null)
               outfile.Dispose();
     }
 }

然后,您可以调用该方法是这样的:

You would then call this method like this:

 Split("C:\\somefile.txt", "C:\\output-files-{0}.txt");