4 Replies - 4709 Views - Last Post: 19 September 2010 - 05:30 AM Rate Topic: -----

#1 Guest_Nephe*


Reputation:

Reading and merging 2 lines of text from a text file.

Posted 18 September 2010 - 10:13 AM

Hello, as the title suggests, I want to read every 2 lines from a text file and then merge them
in a single string with the new line indicator \n between them. Then ideally
I'd like to put that string in an array or a list.

What I have done is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace IO_Test
{
    public partial class Form1 : Form
    {
        List<string> lines = new List<string>();
        StreamReader sr = new StreamReader(@"C:\MyText.txt");
        string[] strArray = new string[6];
        string line;

        public Form1()
        {
            InitializeComponent();

            while ((line = sr.ReadLine()) != null)
            {
                lines.Add(line);
            }

            strArray[0] = lines[0] + "\n" + lines[1];
            strArray[1] = lines[2] + "\n" + lines[3];
            strArray[2] = lines[4] + "\n" + lines[5];
            strArray[3] = lines[6] + "\n" + lines[7];
            strArray[4] = lines[8] + "\n" + lines[9];
            strArray[5] = lines[10] + "\n" + lines[11];
        }
    }
}


Even though it works I'm convinced that the approach is wrong.
Also I'd like not to edit the whole program everytime I add some text in the txt file
but I can't find a way to read and add 2 lines in the list(instead of 1) with a \n between them.

Is there any way to do that? I want the program to automatically process any new text
without being limited from the array's specific length.

(In addition, any comments on how to improve the code are welcome)

Is This A Good Question/Topic? 0

Replies To: Reading and merging 2 lines of text from a text file.

#2 n8wxs   User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Reading and merging 2 lines of text from a text file.

Posted 18 September 2010 - 03:49 PM

Yes, when the while() finishes reading the file the lines list now has a size. You can use the list's Count property to size the string array used to receive the concatenated strings.

See List<(Of <(T>)>).Count Property

I would use Environment.NewLine instead of "\n".

Here's an example:


Edit: added some defensive programming...

private void Form2_Click(object sender, EventArgs e)
{
    List<string> lines = new List<string>();

    string[] strArray;
    string line;

    try
    {
        StreamReader sr = new StreamReader(@"C:\temp\MyText.txt");

        while ((line = sr.ReadLine()) != null)
        {
            // ReadLine() strips the line terminator so we add it back
            lines.Add(line + Environment.NewLine);
        }

        sr.Close();

        switch (lines.Count)
        {
            case 0:
                MessageBox.Show("Nothing read from file!");
                break;

            case 1:
                strArray = new string[1];

                strArray[0] = lines[0] + Environment.NewLine;
                break;

            default:
                int arraySize = lines.Count / 2; // size of array we need

                // now we can allocate the string array
                if (lines.Count % 2 == 0)
                {
                    strArray = new string[arraySize];
                }
                else
                    // add space for last line in file
                    strArray = new string[arraySize + 1];

                // need 2 indicies for both 'arrays'
                for (int i = 0, k = 0; i < lines.Count; i += 2, k++)
                {
                    strArray[k] = lines[i] + Environment.NewLine + lines[i + 1];
                }

                if (arraySize % 2 == 1) // get possible last line
                    strArray[strArray.Length - 1] = lines[lines.Count - 1];

                MessageBox.Show(String.Format("strArray size is {0}", strArray.Length));

                break;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}


This post has been edited by n8wxs: 18 September 2010 - 05:38 PM

Was This Post Helpful? 2
  • +
  • -

#3 fixo   User is offline

  • D.I.C Regular

Reputation: 85
  • View blog
  • Posts: 335
  • Joined: 10-May 09

Re: Reading and merging 2 lines of text from a text file.

Posted 19 September 2010 - 02:52 AM

View PostNephe, on 18 September 2010 - 09:13 AM, said:

Hello, as the title suggests, I want to read every 2 lines from a text file and then merge them
in a single string with the new line indicator \n between them. Then ideally
I'd like to put that string in an array or a list.

Here is my 2 cents


        public static void ConcateLines()
        {
            FileStream fs = new FileStream(@"C:\MyText.txt", FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            FileStream fw = new FileStream(@"C:\MyText_tmp.txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(fw);
            try
            {
                using (sr)
                {
                    using (sw)
                    {
                        List<string> lines = new List<string>();
                        StringBuilder sb = new StringBuilder();
                        string data = sr.ReadToEnd();
                        string[] text = data.Split(new string[] { "\n" }, StringSplitOptions.None);
                        int count = text.Length;
                        if (count == 1) return; //if just one line of text                                          
                        int i =0;
                        while (i < count-1) 
                        {          
                            string str = text[i] + " " + text[i + 1];
                            //append to stringbuilder
                            sb.Append(str + "\n");
                            //add to list
                            lines.Add(str);
                            
                            i+=2;
                        } 
                        if (i-1<count)
                            sb.Append(text[i - 1]);
                        sw.Write(sb.ToString());                       
                    }
                }
                //replace temporary file with source, create backup
                File.Replace(@"C:\MyText_tmp.txt", @"C:\MyText.txt", @"C:\MyText_backup.txt");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                fw.Close();
                fs.Close();
            }
        }



~'J'~
Was This Post Helpful? 2
  • +
  • -

#4 Nephe   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 19-September 10

Re: Reading and merging 2 lines of text from a text file.

Posted 19 September 2010 - 04:38 AM

@n8wxs: Exactly what I was looking for, plain and awesome code thanks alot!

The only hitch I noticed is that if the file didn't contain an even number of lines
the program was throwing an OutOfBounds exception and also for some reason wouldn't display the
penult line from the text file correctly.

I've easily got around that by modifying a bit the for loop; other than that,
everything works like a charm.


@fixo: Not quite what I was looking for but thank you for your effort.
Was This Post Helpful? 0
  • +
  • -

#5 n8wxs   User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Reading and merging 2 lines of text from a text file.

Posted 19 September 2010 - 05:30 AM

Sorry 'bout that! :)

Here's how I fixed my mistakes:

...
default:
    int arraySize = lines.Count / 2; // size of array we need
    int loopLimit = lines.Count;  // for() loop stops here.  :)/>

    // now we can allocate the string array
    if (lines.Count % 2 == 0)
    {
        strArray = new string[arraySize];
    }
    else
    {
        // add space for last line in file
        strArray = new string[arraySize + 1];
        loopLimit -= 1;  // adjust for odd line count
    }

    // need 2 indicies for both 'arrays'
    for (int i = 0, k = 0; i < loopLimit; i += 2, k++)
    {
        strArray[k] = lines[i] + Environment.NewLine + lines[i + 1];
    }

    if (strArray.Length % 2 == 1) // get possible last line
        strArray[strArray.Length - 1] = lines[lines.Count - 1];

    MessageBox.Show(String.Format("strArray size is {0}", strArray.Length));

    break;
...


This post has been edited by n8wxs: 19 September 2010 - 05:31 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1