簡體   English   中英

C#加載txt文件並根據行數將其拆分為X個文件

[英]c# load txt file and split it to X files based on number of lines

這是我到目前為止編寫的代碼...除了一次又一次地重寫同一文件上的每一行外,它沒有完成任何工作...

* RecordCntPerFile = 10K

* FileNumberName = 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;
}

如果我理解正確,則希望將一個大文件拆分為多個較小的文件,最大行數為1萬行。 我在您的代碼中看到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循環。 我只是做了一個簡單的例子來給你這個想法。 提高性能取決於您

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM