mardi 1 décembre 2020

Reading and deleting a Random Line from a .txt File in c#

I wanted to do a random Number Generator in a c# console, wich didn't show a Number a second Time. So i made a Script wich Picks a random Number from a .txt File, reads it and deletes it from the .txt afterwards. I know that there is no Section for Reading the Line and giving an Output, because i first wanted to get the Part with deleting. Can someone pls help me. Script:

using System;
using System.IO;

namespace Random_Number_generator
{
    class Program
    {
        static void Main(string[] args)
        {
            //Generates the random Number
            int RandomNumber;
            string BGInfo;
            Random rnd = new Random();
            int GetRandomInt(int min, int max)
            {
                return rnd.Next(min, max);
            }
            RandomNumber = GetRandomInt(1, 25);

            // 1. Read the content of the file
            string[] readText = File.ReadAllLines("D:/BG_Numbers.txt");
            Console.WriteLine("Readed: " + readText);
            Console.ReadKey();

            // 2. Empty the file
            File.WriteAllText("D:/BG_Numbers.txt", String.Empty);

            using (StreamWriter writer = new StreamWriter("D:/BG_Numbers.txt"))
            {
                foreach (string s in readText)
                {
                    if (!s.Equals(RandomNumber))
                    {
                        writer.WriteLine(s);
                    }
                }
            }
        }
    }
}



Aucun commentaire:

Enregistrer un commentaire