What's new

.NET [C#]Reading text files, Creating text files, Storing in an array

Status
Not open for further replies.
Serkiee

Serkiee

There's a time and place for everything.
Grizzled Veteran Tutorial Creator Contest Sponsor
Messages
1,481
Reaction score
390
Points
275
I'm making a console application that reads from a text file, stores its contents into an array and then randomly chooses a name to win.

I need to have it read names from a .txt file line by line using streamreader and store the names into an array. I also need to check if the file doesn't exists. if it doesn't it needs to create a new .txt file and write the names that the user enters into the file.

I know how to read a file line by line but I don't know how to store each line into an array. I also know how to enter names and store it into an array but I don't know how to make a text file from an array.

If it doesn't make sense I can try explain it more.

Finally this is how it needs to be set out:

if (File.Exists(PATH))
{
}​
else
{
}
GoldBl4d3
 
Z61

Z61

Some times our saints are sinners
Retired
Programmer Forum Addict Odysseus' Summit
Messages
5,476
Reaction score
3,423
Points
1,042
You can always use an ArrayList and then convert that to an Array.
Edit: here's some code I found from searching:
Code:
//Code Source: http://www.dotnetperls.com/streamreader
List<string> list = new List<string>();
	using (StreamReader reader = new StreamReader("file.txt"))
	{
	    string line;
	    while ((line = reader.ReadLine()) != null)
	    {
		list.Add(line); // Add to list.
		Console.WriteLine(line); // Write to console.
	    }
	}
 
Last edited:
Im4eversmart

Im4eversmart

The hacks are real
Glitcher Modder Programmer
Messages
2,161
Reaction score
1,903
Points
455
You want to do something like this:

if ( file does not exist ), ask user for input, create new file input.txt
Read file. Each line, add to string array. Reach end of file.
Create a random integer between 0 and the size of the string array minus 1.
Print out the element of the array at the position of the random integer.
 
Serkiee

Serkiee

There's a time and place for everything.
Grizzled Veteran Tutorial Creator Contest Sponsor
Messages
1,481
Reaction score
390
Points
275
You can always do something with string.Split(<CHAR>);

Code:
List<string> Applicants = new List<string>();

foreach(string Name in new StreamReader("text.txt").ReadToEnd().Split('\n').ToString())
         Applicants.Add(Name);

return Applicants[new Random().Next(0, Applicants.Count() - 1);

You still need help, PM me.

I've already finished it but thanks anyway
 
Status
Not open for further replies.
Top Bottom
Login
Register