本文介绍了如何分割文本文件分割成多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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");

这篇关于如何分割文本文件分割成多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 15:47