I'm learning C# and now I need 开发者_运维问答to build a home project(just to learn how to use file I/O and random). I have a file(names.txt) like this:
Nathan
John
Max
Someone
But how I can access this file(already know) and select a random name, print it and delete this name from the file? Thanks.
Do you definitely need to delete the name from the file? Or can you just delete it from a list in memory?
Anyway, I would separate out the tasks this way:
- Load the text from the file e.g. with
File.ReadAllLines
- Convert to a
List<string>
which will let you remove an element - Create a new instance of
System.Random
- Pick a random element using
Random.Next()
- Fetch (and remove) the name from the list
- Print the name
- Write the file back with
File.WriteAllLines
Now that you know the steps involved, have a go at each of them - and if you get stuck, ask for more details about a specific problem.
Try this :
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Tests.Console
{
class Program
{
static void Main(string[] args)
{
string fileName = "c:\\toto.txt";
var content = File.ReadAllLines(fileName).ToList();
var selected = content[new Random().Next(0, content.Count)];
Debug.Write(selected);
content.Remove(selected);
File.WriteAllLines(fileName, content.ToArray());
}
}
}
精彩评论