0

I'm trying to read a text file to two string arrays. Array1 is to be all the odd lines, array2 all the even lines. I then add all the items of array1 to a combobox and when that is selected, or as it gets typed, outputs array2 to a textbox.

So far, I have tried a few methods from here, but the big issue seems to be creating the arrays. I tried to get help here before, but the answers didn't actually answer my question. They must be arrays, not lists (which I tried and worked well). I am really confused by this whole thing and my attempted code is now rubbish:

private void ReadFile(string filePath, string customerPhone, string customerName)
{
    string line = string.Empty;
    var fileSR = new StreamReader(filePath);
    bool number = true;

    while((line = fileSR.ReadLine()) != null)
    {
        if (number)
        {
            customerPhone(line);
            number = false;
        }
        else
        {
            customerName(line);
            number = true;
        }
   }

   fileSR.Close();
}

I'm losing confidence in this whole process, but I need to find a way to make it work, then I can learn why it does.

2
  • Why not create lists and then convert them into arrays? Note that using File.ReadLines or File.ReadAllLines would be simpler too. If you do use a StreamReader, use a using statement to ensure that the file is closed even if an exception is thrown. Finally, I suspect that the WPF aspect is irrelevant here - unless you're interacting with the UI, this code would be roughly the same regardless of the type of app. Commented Jun 9, 2016 at 14:15
  • I used lists originally and then converted them to string arrays on the window_loaded event. This worked well to populate the combobox with the first array but I could not find a way to have the corresponding index of the second array appear in the textbox. Is there no way to do this except using lists? Commented Jun 9, 2016 at 14:27

3 Answers 3

1

You are almost there, just use the List<string>.

private void ReadFile(string filePath, string customerPhone, string customerName)
{
    string line = string.Empty;
    using (var fileSR = new StreamReader(filePath))
    {
        bool number = true;

        List<string> customerPhone = new List<string>();
        List<string> customerName = new List<string>();
        while((line = fileSR.ReadLine()) != null)
        {
            if (number)
            {
                customerPhone.Add(line);
                number = false;
            }
            else
            {
                customerName.Add(line);
                number = true;
            }
        }

        fileSR.Close();
    }
}

If you are interested only in Arrays, you could simply call customerName.ToArray() to convert it to an array.

Linq Solution

Alternatively you could use Linq and do this.

var bothArrays = File.ReadLines("filepath")        // Read All lines
    .Select((line,index) => new {line, index+1})   // index each line
    .GroupBy(x=> x/2)                              // Convert into two groups
    .SelectMany(x=> x.Select(s=>s.line).ToArray()) // Convert it to array
    .ToArray(); 
Sign up to request clarification or add additional context in comments.

3 Comments

The list is what I did use, then converted them both to arrays in the window_loaded event. I just couldn't work out how to bring up the customerName in a textbox when a number was selected in the combo box
@Hari Prasad: please wrap var fileSR = new StreamReader(filePath) into using: using (var fileSR = new StreamReader(filePath)) {...}
@Jaqtaris, that's following question to what is been asked here, I would suggest post a new question, answer may invalidate this question if we add additional details here and may confuse people reaching this post with similar problems. Hope you understand.
0

You should use collections to return data, say IList<String>:

private static void ReadFile(String filePath, 
  IList<String> oddLines, 
  IList<String> evenLines) {

  oddLines.Clear();
  evenLines.Clear();

  int index = 1; //TODO: start with 0 or with 1

  foreach (String line in File.ReadLines(filePath)) {
    if (index % 2 == 0)
      evenLines.Add(line);
    else
      oddLines.Add(line);

    index += 1; 
  }
}

using

  List<String> names = new List<String>();
  List<String> phones = new List<String>();

  ReadFile(@"C:\MyDate.txt", names, phones);

  // If you want array representation
  String[] myNames = names.ToArray();
  String[] myPhones = phones.ToArray();

  // Let's print out names
  Console.Write(String.Join(Envrironment.NewLine, names));

Please, notice, that using File.ReadLines usually more convenient than StreamReader which should be wrapped in using:

  // foreach (String line in File.ReadLines(filePath)) equals to
  using (var fileSR = new StreamReader(filePath)) {
    while ((line = fileSR.ReadLine()) != null) {
      ...
    }
  }

2 Comments

I understand that this may be the best way, using collections or lists, but can it not be done as arrays?
@Jaqtaris: if you want array, just call .ToArray() on list (see my edit)
0

This worked! I have these class level strings:

string cFileName = "customer.txt";
string[] cName = new string[0];
string[] cPhone = new string[0];

And then this in the Window Loaded event, but could be used in it's own method:

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
    //read file on start
    int counter = 0;
    string line;
    StreamReader custSR = new StreamReader(cFileName);
    line = custSR.ReadLine();

    while (custSR.Peek() != -1)
    {
        Array.Resize(ref cPhone, cPhone.Length + 1);
        cPhone[cPhone.Length - 1] = line;
        counter++;
        line = custSR.ReadLine();
        Array.Resize(ref cName, cName.Length + 1);
        cName[cName.Length - 1] = line;
        counter++;

        line = custSR.ReadLine();

        phoneComboBox.Items.Add(cPhone[cPhone.Length - 1]);
    }
    custSR.Close();

     //focus when program starts
     phoneComboBox.Focus();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.