这是我到目前为止编写的代码...... 除了一遍又一遍地重写同一文件中的每一行之外,它不能完成这项工作......
* RecordCntPerFile = 10K
* FileNumberName = 1(文件编号1)
*完整文件名应该是这样的:1_asci_split
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;
}
答案 0 :(得分:0)
如果我理解正确,您希望将大文件拆分为最小10k行的较小文件。我在你的代码中看到了2个问题:
您永远不会更改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循环。我刚刚做了这个简单的例子给你这个想法。为了提高性能取决于你