C#C
C#3y ago
euskater

❔ Random take a File from a Folder

Hello Dear CSharp Programmers

I have a Question, lets say I have a folder with 1_000 Files. From this folder I would like to randomly pick 1_00. But every file should be taken only once.
How would this method look like ?

I tryed it by myself but it always take one file more then once.

my Code:

 static public int RandomNumber;
 static public int randomIndex;
 static Random random = new Random(DateTime.Now.Millisecond);;

        public string GetRadomFileFromGivenFolderPath()
        {
            if (FolderPath_RandomFiles.Text != " ")
            {
                // Get an array of all file paths in the specified folder
                string[] files = Directory.GetFiles(FolderPath_RandomFiles.Text);

                // If no files are found, return null
                if (files.Length == 0)
                {
                    UpdateRichTextBox("No Files found!");
                    return "null";
                }

                // Generate a random number between 0 and the number of files minus 1
                do
                {
                    // Generate a random number between 0 and the number of files minus 1
                    randomIndex = random.Next(0, files.Length - 1);

                } while (RandomNumber == randomIndex);

                RandomNumber = randomIndex;
                // Return the file path at the random index
                return RandomFilePath = files[randomIndex];
            }
            else
            {
                UpdateRichTextBox("Folder path for \"random Files Path\" not found!");
                return "null";
            }
        }

I wanted to also store all ever picked Files and always check if the newly picked random file has already used once or not but I couldnt manage to code it.

thank you for every help
Was this page helpful?