Search code examples
c#arraysstreamreader

How to read numbers in a .txt file to an integer array?


I have a file that I need to save as an array. I am trying to convert a text file to an integer array using StreamReader. I just am unsure as to what to put in the for loop at the end of the code.

This is what I have so far:

//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
    //code to load the numbers from a file
    OpenFileDialog fd = new OpenFileDialog();

    //open the file dialog and check if a file was selected
    if (fd.ShowDialog() == DialogResult.OK)
    {
    //open file to read
    StreamReader sr = new StreamReader(fd.OpenFile());
    int Records = int.Parse(sr.ReadLine());

    //Assign Array Sizes
    Original = new int[Records];

    int[] OriginalArray;

    for (int i = 0; i < Records; i++)
    {
    //add code here
    }
}

The .txt file is:

    5
    6
    7
    9
    10
    2

PS I am a beginner, so my coding skills are very basic!

UPDATE: I have previous experience using Line.Split and then mapping file to arrays but obviously that does not apply here, so what do I do now?

//as continued for above code
for (int i = 0; i < Records; i++)
{
    int Line = int.Parse(sr.ReadLine());
    OriginalArray = int.Parse(Line.Split(';')); //get error here

    Original[i] = OriginalArray[0];
}

Solution

  • You should just be able to use similar code to what you had above it:

    OriginalArray[i] = Convert.ToInt32(sr.ReadLine());
    

    Every time the sr.ReadLine is called it increments the data pointer by 1 line, hence iterating through the array in the text file.