tags:

views:

51

answers:

2

Hello,

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.

+4  A: 

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.

Jon Skeet
I need to delete it from the file, sorry :(, but thanks for your very good answer!
Nathan Campos
Momentary confusion struck me when I saw the name and the rep - "Who's this Tony the Pony, how did they get 111K rep without me ever seeing them answer a question?" - then I checked the profile and all confusion dissipated :)
Russ Cam
@Russ I see his profile and as I can see he is Jon Skeet, the blog link is to Jon Skeet's blog.
Nathan Campos
+2  A: 

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());
        }
    }
}
Manitra Andriamitondra