user5280270
user5280270

Reputation:

How to read first word of last line from text file?

My input file contains id, description Of Item, Price and date.

I want to get the id of the last line of the file "filename" and increment it.

Here is what I have done so far:

var last = File.ReadLines("file name").Last();
id = last[0] + 1;
Console.WriteLine(last[0]);

It only returns the first word and not the element example 30. It gives 3 and not the whole 30.

Where am I wrong?

Upvotes: 0

Views: 1227

Answers (1)

ChrisF
ChrisF

Reputation: 137148

last is a string and last[0] is the first character of that string. If you want the first word then you'll need to split the string on spaces:

string[] words = last.Split(' ');

Then you can get the first word:

Console.WriteLine(words[0]);

You'll need to include more error checking - in case the last line of the file is empty for example, and perhaps cope with more whitespace characters than just a space. There might be tabs:

var words = last.Split(new char[] { ' ', '\t' });

Upvotes: 2

Related Questions