0

I am trying to read the last line of a text file into an array so that I am able to get a specific element of the array by index, but I am having trouble doing this as 1 line in my text file has many elements that need to go into the array as opposed to there being 1 element per line, so for reference my text file line structure would be like so: element1,element2,element3... It is similar in structure to that of a csv file.

My code so far that is not working:

string lastline = System.IO.File.ReadLines(myfilepath).Last();
string[] id = new string[](lastline.Split(','));

Then after inserting the line to my array I would like to pull an element of the array by the index, for example I want to pull element2 from the array and assign it to var item2, but am not sure how to go about that.

2
  • 2
    If id[index] does not do the job, I have not understood what you want. Commented Apr 22, 2020 at 11:58
  • 3
    string.Split already returns an array of the splitted strings. There is no need to new string[] Commented Apr 22, 2020 at 11:58

1 Answer 1

5

Not sure if I understood your question completely, but getting single string from a string array by index:

string lastline = System.IO.File.ReadLines(myfilepath).Last();
string[] id = lastline.Split(',');

//string result = id[index];
/* Better way */
string result = id.ElementAtOrDefault(index);

Where index is the zero-based index of the items. So, the first string's index would be 0, next 1 etc. Thanks to Steve for pointing out the error in creating the array and the hint to avoid IndexOutOfRangeException.
The method ElementAtOrDefault(index) will return the element at index, or if the index is out of range, return a default element, which in this case is an empty string.

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

3 Comments

Thanks Sami! it works, appreciate the quick response. I'll accept the answer when the timer allows me to.
Another thing to add to your answer is a warning about the IndexOutOfRangeException that is so common in this kind of code (and an example of to avoid it)
The only downside with this is if the file is large you'll have to read the whole thing into memory just to get the last line.

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.