C# c加载txt文件并根据行数将其拆分为X文件
这是我到目前为止写的代码。。。 除了一遍又一遍地重写同一文件中的每一行外,它不起作用 *RecordCntPerFile=10K *FileNumberName=1文件编号1 *完整文件名应该是这样的:1_asci_splitC# c加载txt文件并根据行数将其拆分为X文件,c#,split,conditional-statements,C#,Split,Conditional Statements,这是我到目前为止写的代码。。。 除了一遍又一遍地重写同一文件中的每一行外,它不起作用 *RecordCntPerFile=10K *FileNumberName=1文件编号1 *完整文件名应该是这样的:1_asci_split string FileFullPath = DestinationFolder + "\\" + FileNumberName + FileNamePart + FileExtension; using (System.IO.StreamReader sr = ne
string FileFullPath = DestinationFolder + "\\" + FileNumberName + FileNamePart + FileExtension;
using (System.IO.StreamReader sr = new System.IO.StreamReader(SourceFolder + "\\" + SourceFileName))
{
for (int i = 0; i <= (RecordCntPerFile - 1); i++)
{
using (StreamWriter sw = new StreamWriter(FileFullPath))
{
{ sw.Write(sr.Read() + "\n"); }
}
}
FileNumberName++;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
如果我理解正确,您希望将一个大文件拆分为最大为10k行的较小文件。我发现您的代码有两个问题: 您永远不会更改FullFilePath变量。所以你总是在同一个文件上重写 您总是将整个源文件读写到目标文件 我重写了你的代码,以符合我前面所说的行为。您只需修改字符串
int maxRecordsPerFile = 10000;
int currentFile = 1;
using (StreamReader sr = new StreamReader("source.txt"))
{
int currentLineCount = 0;
List<string> content = new List<string>();
while (!sr.EndOfStream)
{
content.Add(sr.ReadLine());
if (++currentLineCount == maxRecordsPerFile || sr.EndOfStream)
{
using (StreamWriter sw = new StreamWriter(string.Format("file{0}.txt", currentFile)))
{
foreach (var line in content)
sw.WriteLine(line);
}
content = new List<string>();
currentFile++;
currentLineCount = 0;
}
}
}
当然,您可以做得更好,因为您不需要创建该字符串并执行foreach循环。我只是做了一个简单的例子来告诉你这个想法。提高性能取决于您因此,如果count=10K,那么您是否希望从现有文件创建10K新文件?每个文件应该有多少行?如果单个文件没有10K行,该怎么办?