Andy5
Andy5

Reputation: 2405

How to read a text file into a List in C#

I have a text file that has the following format:

1234

ABC123 1000 2000

The first integer value is a weight and the next line has three values, a product code, weight and cost, and this line can be repeated any number of times. There is a space in between each value.

I have been able to read in the text file, store the first value on the first line into a variable, and then the subsequent lines into an array and then into a list, using first readline.split('').

To me this seems an inefficient way of doing it, and I have been trying to find a way where I can read from the second line where the product codes, weights and costs are listed down into a list without the need of using an array. My list control contains an object where I am only storing the weight and cost, not the product code.

Does anyone know how to read in a text file, take in some values from the file straight into a list control?

Thanks

Upvotes: 1

Views: 1376

Answers (4)

whyleee
whyleee

Reputation: 4049

If you don't want to parse strings from the file and to reserve an additional memory for holding split strings you can use a binary format to store your information in the file. Then you can use the class BinaryReader with methods like ReadInt32(), ReadDouble() and others. It is more efficient than read by characters.

But one thing: binary format is bad readable by humans. It will be difficult to edit the file in the editor. But programmatically - without any problems.

Upvotes: 0

Jerod Venema
Jerod Venema

Reputation: 44632

The other answers are correct - there's no generalized solution for this.

If you've got a relatively small file, you can use File.ReadAllLines(), which will at least get rid of a lot cruft code, since it'll immediately convert it to a string array for you.

Upvotes: 0

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

What you do is correct. There is no generalized way of doing it, since what you did is that you descirbed the algorithm for it, that has to be coded or parametrized somehow.

Upvotes: 1

Oded
Oded

Reputation: 499002

Since your text file isn't as structured as a CSV file, this kind of manual parsing is probably your best bet.

C# doesn't have a Scanner class like Java, so what you wan't doesn't exist in the BCL, though you could write your own.

Upvotes: 0

Related Questions