954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

read file

Hi,

I am new to c# and I am trying to read a file which is of format:

1 2 3
3 4 5
6 7 8

1 2
3 4

the problem is I am not able to read file in given format, I am not able to tell the streamReader to read separately. Like for example if I ask to read till end of file I can't seperate the format altogether. I have to store first format in different arrays and the other format into different arrays for example:
arrayList A will store 1,3,6
arrayList B will store 2,4,7
arrayList C will store 3,5,8

and 2 other arrays will store
arrayList D will store 1,3
arrayList f will store 2,4

I tried to search it but I didn't got any success till now.
some code that I tried was:

StreamReader myFile = new StreamReader(fileInputTextBox.Text);
   //Reads the file line by line
  while (!myFile.EndOfStream)
    {
        string myString = myFile.ReadLine(); //reads file line by line
         fillArray(myString);
     }
    myFile.Close();


This is the code I am using to read file, since I don't know how to make the streamReader read till my format change I am just reading till end of stream.
another method that I use to store it into an array:

public void formArray(string fileString)
        {
            string filestring=fileString;
            string[] tokens = new string[3];
            tokens =filestring.Split(' '); //split string with delimiter as space
            A.Add(tokens[0]);
            B.Add(tokens[1]);
            C.Add(tokens[2]);
          //don't know how to work for D and F 
         }


I am really confused can anyone suggest how can I do that.

Thanks!!

NT.
Newbie Poster
15 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

Is the data structure static in that it will always be in the format exampled?

DdoubleD
Posting Shark
996 posts since Jul 2009
Reputation Points: 341
Solved Threads: 233
 

You could check tokens.Length and then act accordingly.
Should also advise you to use the generic List<> type instead of ArrayList.

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

This is an odd task. As danny pointed out the generic list is definetly the way to go! You could do something like this:

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 daniweb
{
  public partial class frmWeirdHomework : Form
  {
    public frmWeirdHomework()
    {
      InitializeComponent();
    }

    private static string[] GetSampleData()
    {
      List<string> sl = new List<string>();
      sl.Add("1 2 3");
      sl.Add("3 4 5");
      sl.Add("6 7 8");
      sl.Add("");
      sl.Add("1 2 ");
      sl.Add("3 4 ");
      return sl.ToArray();
    }

    private static bool IsNumericArray(string[] arr)
    {
      if ((arr == null) || (arr.Length == 0))
        return false;

      int i;

      foreach (string s in arr)
      {
        if (!int.TryParse(s, out i))
          return false;
      }
      return true;
    }

    private void button2_Click(object sender, EventArgs e)
    {
      //string[] data = File.ReadAllLines(@"C:\yourfile.txt");
      string[] data = GetSampleData();
      List<List<int>> lstAllItems = new List<List<int>>(); //master list
      
      List<List<int>> workingSet = new List<List<int>>(); //holds our working lists until the format changes

      foreach (string line in data)
      {
        if (string.IsNullOrEmpty(line))
          continue;
        string[] sVals = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (!IsNumericArray(sVals))
          continue;

        int[] iVals = Array.ConvertAll<string, int>(sVals, Convert.ToInt32);
        if (workingSet.Count != iVals.Length) //our format changed
        {
          lstAllItems.AddRange(workingSet.ToArray());
          workingSet.Clear();
          for (int i1 = 0; i1 < iVals.Length; i1++)
          {
            workingSet.Add(new List<int>());
          }
        }
        for (int i1 = 0; i1 < iVals.Length; i1++)
        {
          workingSet[i1].Add(iVals[i1]);
        }
      }
      if (workingSet.Count != 0)
        lstAllItems.AddRange(workingSet.ToArray());
      

      for (int i1 = 0; i1 < lstAllItems.Count; i1++)
      {
        List<int> lst = lstAllItems[i1];
        Console.WriteLine("Array[{0:F0}]: {1}", i1, string.Join(", ", lst.ConvertAll<string>(Convert.ToString).ToArray()));
      }
    }

  }
}
Array[0]: 1, 3, 6
Array[1]: 2, 4, 7
Array[2]: 3, 5, 8
Array[3]: 1, 3
Array[4]: 2, 4


I'm sure you can figure out how to make 0->A, 1->B, etc :)

sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
 
You could check tokens.Length and then act accordingly. Should also advise you to use the generic List<> type instead of ArrayList.


Thanks a lot for the advice. It worked out. I thought if you do not specify array size while you initialize it gives error but it didn't gave a error. Can you tell me why you asked me to used list instead of arraylist. what's the advantage? It might be silly question but I really wanna know.

NT.
Newbie Poster
15 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

This is an odd task. As danny pointed out the generic list is definetly the way to go! You could do something like this:

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 daniweb
{
  public partial class frmWeirdHomework : Form
  {
    public frmWeirdHomework()
    {
      InitializeComponent();
    }

    private static string[] GetSampleData()
    {
      List<string> sl = new List<string>();
      sl.Add("1 2 3");
      sl.Add("3 4 5");
      sl.Add("6 7 8");
      sl.Add("");
      sl.Add("1 2 ");
      sl.Add("3 4 ");
      return sl.ToArray();
    }

    private static bool IsNumericArray(string[] arr)
    {
      if ((arr == null) || (arr.Length == 0))
        return false;

      int i;

      foreach (string s in arr)
      {
        if (!int.TryParse(s, out i))
          return false;
      }
      return true;
    }

    private void button2_Click(object sender, EventArgs e)
    {
      //string[] data = File.ReadAllLines(@"C:\yourfile.txt");
      string[] data = GetSampleData();
      List<List<int>> lstAllItems = new List<List<int>>(); //master list
      
      List<List<int>> workingSet = new List<List<int>>(); //holds our working lists until the format changes

      foreach (string line in data)
      {
        if (string.IsNullOrEmpty(line))
          continue;
        string[] sVals = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (!IsNumericArray(sVals))
          continue;

        int[] iVals = Array.ConvertAll<string, int>(sVals, Convert.ToInt32);
        if (workingSet.Count != iVals.Length) //our format changed
        {
          lstAllItems.AddRange(workingSet.ToArray());
          workingSet.Clear();
          for (int i1 = 0; i1 < iVals.Length; i1++)
          {
            workingSet.Add(new List<int>());
          }
        }
        for (int i1 = 0; i1 < iVals.Length; i1++)
        {
          workingSet[i1].Add(iVals[i1]);
        }
      }
      if (workingSet.Count != 0)
        lstAllItems.AddRange(workingSet.ToArray());
      

      for (int i1 = 0; i1 < lstAllItems.Count; i1++)
      {
        List<int> lst = lstAllItems[i1];
        Console.WriteLine("Array[{0:F0}]: {1}", i1, string.Join(", ", lst.ConvertAll<string>(Convert.ToString).ToArray()));
      }
    }

  }
}
Array[0]: 1, 3, 6
Array[1]: 2, 4, 7
Array[2]: 3, 5, 8
Array[3]: 1, 3
Array[4]: 2, 4

I'm sure you can figure out how to make 0->A, 1->B, etc :)


I am really thankful for such a nice example. But I wouldlike to ask the same question to you as well. why we are using list instead of arraylist? Please can you give some brief explanation?

NT.
Newbie Poster
15 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

Hello.
Both ArrayList and List classes are provided to work with dynamic arrays. But, in ArrayList all elements have type of System.Object. And in List you specify the type of elements by yourself. Let's see what it gives to you:

1. Suppose, you have an array of strings.
For ArrayList: while adding new element to array - it will be
cast to an Object type and then added to list. Then to take the
value of it - you'd have to cast it back to String.

ArrayList list = new ArrayList();
            list.Add("String element");

            string element = (string)list[0];

For List: you're just define a List of strings and there's no need
in boxing/unboxing operations (casting to Object type and back).

List<string> otherList = new List<string>();
            otherList.Add("String element");
            string otherElement = otherList[0];


2. Since the every reference type can be cast to System.Object and every value type can be boxed into an Object, it's possible to have something like this (in ArrayList):

ArrayList list = new ArrayList();
            list.Add("String element");
            list.Add(2);


The List is strong-typed, so it's one more advantage. E.g. it wouldn't allow you to add Integer in your list of Strings. You will be warned at compilation time that you're trying to do something illegal.

List<string> otherList = new List<string>();
            otherList.Add("String element");
            otherList.Add(2); // compilation time error


3. And here's a nice post, where performance of List And ArrayList was compared: ArrayList’s vs. generic List for primitive types and 64-bits

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

Hello. Both ArrayList and List classes are provided to work with dynamic arrays. But, in ArrayList all elements have type of System.Object. And in List you specify the type of elements by yourself. Let's see what it gives to you:

1. Suppose, you have an array of strings. For ArrayList: while adding new element to array - it will be cast to an Object type and then added to list. Then to take the value of it - you'd have to cast it back to String.

ArrayList list = new ArrayList();
            list.Add("String element");

            string element = (string)list[0];

For List: you're just define a List of strings and there's no need in boxing/unboxing operations (casting to Object type and back).

List<string> otherList = new List<string>();
            otherList.Add("String element");
            string otherElement = otherList[0];

2. Since the every reference type can be cast to System.Object and every value type can be boxed into an Object, it's possible to have something like this (in ArrayList):

ArrayList list = new ArrayList();
            list.Add("String element");
            list.Add(2);

The List is strong-typed, so it's one more advantage. E.g. it wouldn't allow you to add Integer in your list of Strings. You will be warned at compilation time that you're trying to do something illegal.

List<string> otherList = new List<string>();
            otherList.Add("String element");
            otherList.Add(2); // compilation time error

3. And here's a nice post, where performance of List And ArrayList was compared: ArrayList’s vs. generic List for primitive types and 64-bits


Hey, thanks a lot!! I really get a good idea now why not to use arraylist when it is a better idea using list. That was a nice explanation.:)

NT.
Newbie Poster
15 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

You're welcome :)
Good luck with learning C#.

Please, mark this thread as solved if the issue is settled.

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

>> Antenka
Great explanation :)

Please mark this thread as solved if you have found an answer to your question and good luck!

sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
 

Anteka, very good reply! I had to look up the SOS (Spiritually Optimized System) acronym though--LOL.

DdoubleD
Posting Shark
996 posts since Jul 2009
Reputation Points: 341
Solved Threads: 233
 

Thanks, guys :)
Hehe .. Spiritually Optimized .. interesting thingy :P

Antenka
Posting Whiz
362 posts since Nov 2008
Reputation Points: 293
Solved Threads: 82
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: