Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C# Beginner here so please bear with me.
I have a series of .txt files that contain number values, and I would like to designate them from the command line and then place the contents of each .txt file into an individual array for my program to sort later.
(the .txt files contain numbers that must be sorted lowest to highest and vice versa)
How can I do this?
I have tried googling the answer but have not found a solution.
Any help appreciated.

What I have tried:

I have yet to try anything as I am unsure how to start.
Posted
Updated 18-Jul-18 3:51am

Hi
Welcome to C#!

The StreamReader class is one that you can use to read data into your application

using(var reader = new StreamReader("C:\\PathOfFile.txt"))
{

}


You can use the method ReadLine() in a loop to read the lines into a collection or ReadToEnd() to read the whole thing and split the lines up afterwards.
 
Share this answer
 
v2
Another option is to use the File.ReadLines method (see File.ReadLines Method (System.IO) | Microsoft Docs[^]).

You can then either use a foreach loop to iterate through the lines, like so:
foreach(string line in File.ReadLines("myFile.txt"))
{
  // Do something with line
}

Or you can use LINQ to populate an array directly (make sure to include a using for System.Linq). For example, to make an array from a file where each line contains a single integral number, you could do the following:
int[] myNumbers = File.ReadLines("myFile.txt")
  .Select(line => int.Parse(line))
  .ToArray();
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900