gpt4 book ai didi

c# - 如何将一个文本文件拆分成多个文件?

转载 作者:太空狗 更新时间:2023-10-29 23:03:40 30 4
gpt4 key购买 nike

在 C# 中,将一个文本文件拆分为多个文本文件(拆分分隔符为空行)同时保留字符编码的最有效方法是什么?

最佳答案

我会使用 StreamReader 和 StreamWriter 类:

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

然后你可以像这样调用这个方法:

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

关于c# - 如何将一个文本文件拆分成多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4310684/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com