0

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];
}

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OMG just saw your answer now! Thank you soo much! Your answer was super simple and made me realise how much I was overthinking lol!
0

try this

OpenFileDialog fd = new OpenFileDialog();

if (fd.ShowDialog() == DialogResult.OK)
{
    StreamReader reader = new StreamReader(fd.OpenFile());

    var list = new List<int>();

    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        int value = 0;
        if (!string.IsNullOrWhiteSpace(line) && int.TryParse(line, out value))
            list.Add(value);
    }

    MessageBox.Show(list.Aggregate("", (x, y) => (string.IsNullOrWhiteSpace(x) ? "" : x + ", ") + y.ToString()));
}

Comments

0

You can read the entire file into a string array, then parse (checking the integrity of each one).

Something like:

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

    //open the file dialog and check if a file was selected
    if (fd.ShowDialog() == DialogResult.OK)
    {
        var file = fd.FileName;

        try
        {
            var ints = new List<int>();
            var data = File.ReadAllLines(file);

            foreach (var datum in data)
            {
                int value;
                if (Int32.TryParse(datum, out value))
                {
                    ints.Add(value);
                }
            }

            Original = ints.ToArray();

        }
        catch (IOException)
        {
            // blah, error
        }
    }
}

Comments

0

Another way to do it if you'd like to read to the end of the file and you don't know how long it is with a while loop:

String line = String.Empty;
int i=0;
while((line = sr.ReadLine()) != null)
{
    yourArray[i] = Convert.ToInt32(line);
    i++;

    //but if you only want to write to the file w/o any other operation
    //you could just write w/o conversion or storing into an array
    sw.WriteLine(line); 
    //or sw.Write(line + " "); if you'd like to have it in one row
}

Comments

0
//using linq & anonymous methods (via lambda)
string[] records = File.ReadAllLines(file);
int[] unsorted = Array.ConvertAll<string, int>(records, new Converter<string, int>(i => int.Parse(i)));

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.