Results 1 to 19 of 19

Thread: Creating lines of a text file into an array?

  1. #1
    Lively Member
    Join Date
    Jan 12
    Posts
    66

    Creating lines of a text file into an array?

    C# Code:
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.IO;
    6.  
    7. namespace CompareRegistryFiles
    8. {
    9.     class Program
    10.     {
    11.         static void Main(string[] args)
    12.         {
    13.             string sDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    14.             string sFilePath = sDesktopPath + "\\" + "3.txt";
    15.             using (StreamReader oStreamReader = new StreamReader(sFilePath))
    16.             {
    17.                 string line;
    18.                 string[] arr = new String[3];
    19.                 int x = 0;
    20.                 while ((line = oStreamReader.ReadLine()) != null)
    21.                 {
    22.                     // 3.txt
    23.                     // a
    24.                     // b
    25.                     // [space]
    26.                     // d
    27.  
    28.                     Console.WriteLine(x + " " + line);
    29.  
    30.                     // if string[] arr = new String[3]
    31.                     // error: Index was outside the bounds of the array.
    32.                     arr[x] = line;
    33.                     x++;
    34.                 }
    35.                 Console.ReadLine();
    36.             }
    37.         }
    38.     }
    39. }

    Please see the comments above.
    If
    if string[] arr = new String[4],
    no error.
    But there is only 4 lines and the arr index x starts from 0. So the size of arr should be no more than 3.
    Could anyone explain to me why the error occurs?
    Thanks.

  2. #2
    Fanatic Member
    Join Date
    Jun 04
    Location
    All useless places
    Posts
    916

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by MSDN
    Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
    http://msdn.microsoft.com/en-us/library/9b9dty7d.aspx

  3. #3
    Fanatic Member ThomasJohnsen's Avatar
    Join Date
    Jul 10
    Location
    Denmark
    Posts
    521

    Re: Creating lines of a text file into an array?

    Declaring an array of size 4 allows for indices {0, 1, 2, 3}.
    This may sound illogical, but upon declaring an array you don't specify the upper bound; rather the number of variables, the array will be able to store. And with a zero-based array indexing like in C, arrays allways have highest index equal to the length - 1. You can verify this with the GetUpperBound method.

    Tom

    #EDIT: Slow typing...
    In truth, a mature man who uses hair-oil, unless medicinally , that man has probably got a quoggy spot in him somewhere. As a general rule, he can't amount to much in his totality. (Melville: Moby Dick)

  4. #4
    Fanatic Member
    Join Date
    Jun 04
    Location
    All useless places
    Posts
    916

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by ThomasJohnsen View Post
    #EDIT: Slow typing...
    But more explanatory

  5. #5
    Lively Member
    Join Date
    Jan 12
    Posts
    66

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by ThomasJohnsen View Post
    Declaring an array of size 4 allows for indices {0, 1, 2, 3}.
    #EDIT: Slow typing...
    Can you tell me how to return the indices?
    Say:
    return something like this from an array?
    Code:
    // {0, 1, 2, 3}

  6. #6
    Fanatic Member
    Join Date
    Jun 04
    Location
    All useless places
    Posts
    916

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by tinfanide View Post
    Can you tell me how to return the indices?
    Say:
    return something like this from an array?
    Code:
    // {0, 1, 2, 3}
    Why would you need the numbering of indices? If you do GetUpperBound() on array, you get the max index and then you know your array indices are from 0 to that number. Or you can also do arrayVariable.Length that will give you the total number of elements present in the array.

  7. #7
    Fanatic Member ThomasJohnsen's Avatar
    Join Date
    Jul 10
    Location
    Denmark
    Posts
    521

    Re: Creating lines of a text file into an array?

    Well the method {your array name}.GetLowerBound will return 0 and the method {your array name}.GetUpperBound will return 3.

    If you want to loop safely through all the items in an array, you can use foreach instead of for (omitting the use of bounds). And there are ways to read all lines of a textfile into an array with a single command (assuming your file is non-binary, you could for example use: ReadAllLines (http://msdn.microsoft.com/en-us/libr...dalllines.aspx)).

    Tom

    #EDIT: Slow twice .... no yellow jersey for me.
    In truth, a mature man who uses hair-oil, unless medicinally , that man has probably got a quoggy spot in him somewhere. As a general rule, he can't amount to much in his totality. (Melville: Moby Dick)

  8. #8
    Lively Member
    Join Date
    Jan 12
    Posts
    66

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by ThomasJohnsen View Post
    Declaring an array of size 4 allows for indices {0, 1, 2, 3}.
    This may sound illogical, but upon declaring an array you don't specify the upper bound; rather the number of variables, the array will be able to store. And with a zero-based array indexing like in C, arrays allways have highest index equal to the length - 1. You can verify this with the GetUpperBound method.

    Tom

    #EDIT: Slow typing...
    Quote Originally Posted by rjv_rnjn View Post
    Why would you need the numbering of indices? If you do GetUpperBound() on array, you get the max index and then you know your array indices are from 0 to that number. Or you can also do arrayVariable.Length that will give you the total number of elements present in the array.
    No, there's no need doing so. After some experiments with what ya all have just said, I quite get what you mean by that. I know arrays start from 0 in some other languages. But just got messed up in C#, though.

  9. #9
    Lively Member
    Join Date
    Jan 12
    Posts
    66

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by ThomasJohnsen View Post
    Well the method {your array name}.GetLowerBound will return 0 and the method {your array name}.GetUpperBound will return 3.

    If you want to loop safely through all the items in an array, you can use foreach instead of for (omitting the use of bounds). And there are ways to read all lines of a textfile into an array with a single command (assuming your file is non-binary, you could for example use: ReadAllLines (http://msdn.microsoft.com/en-us/libr...dalllines.aspx)).

    Tom

    #EDIT: Slow twice .... no yellow jersey for me.
    Really feel grateful for the reference given by ya. Really helpful.
    The use of
    Code:
    string readText = File.ReadAllLines(sFileName);
    resolved all my questions in my head cos
    I was just about to ask if
    in C#
    we could or not declare an array without a size.

  10. #10
    Fanatic Member
    Join Date
    Jun 04
    Location
    All useless places
    Posts
    916

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by tinfanide View Post
    The use of
    Code:
    string readText = File.ReadAllLines(sFileName);
    resolved all my questions in my head cos
    I was just about to ask if
    in C#
    we could or not declare an array without a size.
    In most cases ReadAllLines() will suffice. But this can come back if your file sizes are too big. Say if you are reading a file of 100MB, you would not want to read the entire file in memory at once. In that case you may want to read that line by line and store each line in a list.

    You can store your lines as a List of strings. Something like,
    Code:
    List<string> fileLines = new List<string>();
                    while ((line = oStreamReader.ReadLine()) != null)
                    {
                        fileLines.Add(line);
                    }
    I know this may be a bit too much to begin with but keep in mind to check Generics later.

    There are a whole list of collection classes in .Net that you can use where you don't have to specify the length of the collection in advance.
    http://msdn.microsoft.com/en-us/library/6tc79sx1.aspx

  11. #11
    Lively Member
    Join Date
    Jan 12
    Posts
    66

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by rjv_rnjn View Post
    In most cases ReadAllLines() will suffice. But this can come back if your file sizes are too big. Say if you are reading a file of 100MB, you would not want to read the entire file in memory at once. In that case you may want to read that line by line and store each line in a list.

    You can store your lines as a List of strings. Something like,
    Code:
    List<string> fileLines = new List<string>();
                    while ((line = oStreamReader.ReadLine()) != null)
                    {
                        fileLines.Add(line);
                    }
    I know this may be a bit too much to begin with but keep in mind to check Generics later.

    There are a whole list of collection classes in .Net that you can use where you don't have to specify the length of the collection in advance.
    http://msdn.microsoft.com/en-us/library/6tc79sx1.aspx
    Yes, it does sound a bit too much for me to begin with.
    ArrayList, StringCollection, List, Enumerator...
    Each of them seems slightly different from one another.
    But anyway, it's always good to have people here refer me to some references.
    Thanks.

  12. #12
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 11
    Posts
    605

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by rjv_rnjn View Post
    In most cases ReadAllLines() will suffice. But this can come back if your file sizes are too big. Say if you are reading a file of 100MB, you would not want to read the entire file in memory at once. In that case you may want to read that line by line and store each line in a list.

    You can store your lines as a List of strings. Something like,
    Code:
    List<string> fileLines = new List<string>();
                    while ((line = oStreamReader.ReadLine()) != null)
                    {
                        fileLines.Add(line);
                    }
    I know this may be a bit too much to begin with but keep in mind to check Generics later.

    There are a whole list of collection classes in .Net that you can use where you don't have to specify the length of the collection in advance.
    http://msdn.microsoft.com/en-us/library/6tc79sx1.aspx
    I would use a List<T> capacity if that were the case, this would still load ~100MB into memory, which may not be what you want, load items up to the capacity, then deal with them and continue loading up to the capacity, then repeat.
    <<<------------
    < Please rate my post if this helped you out. Any kind of thanks is gladly appreciated >



    VB Programming (2012 - Present)
    ®Crestron - DMC-T Certified Programmer | Software Developer
    <<<------------

  13. #13
    Lively Member
    Join Date
    Jan 12
    Posts
    66

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by AceInfinity View Post
    I would use a List<T> capacity if that were the case, this would still load ~100MB into memory, which may not be what you want, load items up to the capacity, then deal with them and continue loading up to the capacity, then repeat.
    Yes.
    But I would like to ask... in the example shown in this reference:
    http://msdn.microsoft.com/en-us/library/y52x03h2.aspx

    The .Count refers to the actual size of the List items. But why is the Capacity up to 8 (where the actual size of the List in that example is 5 only)?

  14. #14
    Fanatic Member
    Join Date
    Jun 04
    Location
    All useless places
    Posts
    916

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by tinfanide View Post
    in the example shown in this reference:
    http://msdn.microsoft.com/en-us/library/y52x03h2.aspx

    The .Count refers to the actual size of the List items. But why is the Capacity up to 8 (where the actual size of the List in that example is 5 only)?
    Since MSDN does not say anything on this, I would guess that's non-deterministic or maybe there is some algo used by BCL to increment the capacity based on the number of elements the List contains.

  15. #15
    Fanatic Member
    Join Date
    Jun 04
    Location
    All useless places
    Posts
    916

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by AceInfinity View Post
    I would use a List<T> capacity if that were the case, this would still load ~100MB into memory, which may not be what you want, load items up to the capacity, then deal with them and continue loading up to the capacity, then repeat.
    My point was read a line, do the processing on the line and then read next line. And how do you suggest to achieve reading the file partially? Or did you mean something else? My point is, as far as I know, if you are reading a file, either you read it whole into the memory or read it line by line. I do not know of a way to read partial file, process the lines read, and then read from the last file location offset till next.

  16. #16
    Lively Member
    Join Date
    Jan 12
    Posts
    66

    Re: Creating lines of a text file into an array?

    Yes, I saw.

  17. #17
    Fanatic Member AceInfinity's Avatar
    Join Date
    May 11
    Posts
    605

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by rjv_rnjn View Post
    My point was read a line, do the processing on the line and then read next line. And how do you suggest to achieve reading the file partially? Or did you mean something else? My point is, as far as I know, if you are reading a file, either you read it whole into the memory or read it line by line. I do not know of a way to read partial file, process the lines read, and then read from the last file location offset till next.
    You shouldn't have to store the full thing into a list. If you want it to contain more than one value, then by 'buffer' I mean setting a capacity of items (to make sure that our list doesn't exceed a certain number of elements), and clearing the list when capacity is reached to start adding items from index 0 into the array again, as the StreamReader continues to read each line one by one.

    If you don't need this then you don't have to store anything, deal with the lines one by one, do what you need to do with each line (string), and keep reading.

    Here's pseudo logic of what i'm talking about:

    1) A file with 13 lines (odd number for easier understanding of a possible problem that I foolishly forgot about the first time I tried this).
    2) Set a StreamReader instance with a capacity of 2
    3) Read through the lines of this text file adding each to the List as usual
    4) if we reach our capacity then deal with the data in the list
    5) CLEAR it...
    6) Continue reading
    7) Repeat

    That way we're not continuously dealing with this data if you don't store anything. But you're also not storing the entire collection of lines into a List before dealing with the data.

    But note this...

    8) Once the StreamReader is finished reading, in this case we would never reach the capacity here because 13 is not divisible by 2. So we check to see if the list contains anything leftover from the end of the file, and deal with whatever is left over, if anything.

    Now we can get rid of the list all together if you want.

    EDIT:
    vb Code:
    1. Dim MyList As New List(Of String)(5)
    2. Using sr As New StreamReader("C:\Myfile.txt")
    3.     While sr.Peek < -1
    4.         While MyList.Count < MyList.Capacity
    5.             MyList.Add(sr.ReadLine)
    6.         End While
    7.         'Deal with contents of MyList here
    8.         MyList.Clear()
    9.     End While
    10. End Using
    11.  
    12. If MyList.Count > 0 Then
    13.     'Deal with remaining contents of MyList here
    14.     MyList.Clear() 'Optional, but for this example there's no further purpose for MyList
    15. End If

    Perhaps useful for reading and writing modifications in partial? Without dealing with all data at once? I don't know, but this is what I was trying to explain earlier whether somebody finds a use for this strategy here or not.

    ("Buffer" indicated by the capacity of 5 here. I could have put it into a separate variable to store it's numerical value to be placed within the capacity brackets there, but I wrote this quick and I don't see an urgent need for that for just an example.)

    Cheers
    ~Ace
    Last edited by AceInfinity; Jul 25th, 2012 at 09:50 PM.
    <<<------------
    < Please rate my post if this helped you out. Any kind of thanks is gladly appreciated >



    VB Programming (2012 - Present)
    ®Crestron - DMC-T Certified Programmer | Software Developer
    <<<------------

  18. #18
    Fanatic Member
    Join Date
    Jun 04
    Location
    All useless places
    Posts
    916

    Re: Creating lines of a text file into an array?

    Ok, I see what you meant.

  19. #19
    Fanatic Member ThomasJohnsen's Avatar
    Join Date
    Jul 10
    Location
    Denmark
    Posts
    521

    Re: Creating lines of a text file into an array?

    Quote Originally Posted by tinfanide View Post
    Yes.
    But I would like to ask... in the example shown in this reference:
    http://msdn.microsoft.com/en-us/library/y52x03h2.aspx

    The .Count refers to the actual size of the List items. But why is the Capacity up to 8 (where the actual size of the List in that example is 5 only)?
    The capacity will be doubled when it is exceeded. Thus a list with 167 elements will have capacity of 256 elements - a list with 319 elements will have capacity of 512 elements. This is completely deliberate to ensure that insertions into the list will be roughly O(1).

    Tom
    In truth, a mature man who uses hair-oil, unless medicinally , that man has probably got a quoggy spot in him somewhere. As a general rule, he can't amount to much in his totality. (Melville: Moby Dick)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •