txt File partition

Hi,

I need to read a .txt file , partition it into smaller .txt files ,and then saving them.

The partition process depends on finding the carriage return (enter) character.

How can I doing that

Thanks in advance ,

Aya.



Answer this question

txt File partition

  • gexaman

    Try this:

    using(System.IO.StreamReader reader = new System.IO.StreamReader("textfile.txt"))
    {
     string allText = reader.ReadToEnd();
     string[] splitByLines = allText.Split(new char[]{'\n'},StringSplitOptions.RemoveEmptyEntries);
    
     for(int i = 0; i < splitByLines.Length; i++)
     {
     using(System.IO.StreamWriter writer = new System.IO.StreamWriter(String.Format("line{0}.txt", i+1), false, System.Text.UnicodeEncoding.Unicode))
     {
      writer.WriteLine(splitByLines[i ]);
      writer.Flush();
     }
     }
    }

    This will read a text file, "textfile.txt" and split it into lines. It will then write each line to a new text file, "lineX.txt" where X is the line number. Hope that helps.



  • Vinod Anand

    You might want to be careful doing the way that Kevin suggested as this will cause problems when reading large text files. His solution will read the entire text file into memory and then make another copy of it. So if the text file you reading is 10 MB, you application will consume 20 MB memory when calling this method.

    It might be better to read a line in at a time:



    using (System.IO.StreamReader reader = new System.IO.StreamReader("textfile.txt"))
    {
        string line;
        int count = 0;
     
        while ((line = reader.ReadLine()) != null)
        {
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(String.Format("line{0}.txt", count + 1), false, System.Text.UnicodeEncoding.Unicode))
            {
                writer.WriteLine(line);
            }
        }
    }

     



  • txt File partition