Random File Repeat Win Form in c#

Kailash Sahu 141 Reputation points
2021-07-25T13:36:14.31+00:00

Random rand = new Random();
string[] filess = Directory.GetFiles("Select Directory");
string randomFile = filess[rand.Next(filess.Length)];

Developer technologies | C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-07-25T14:52:23.777+00:00

    Hello,

    Sample project for below is in this repository

    Using the following class to store files

    public class FileItem  
    {  
        public string FolderName { get; set; }  
        public string FileName { get; set; }  
        public bool Selected { get; set; }  
        public override string ToString() => FileName;  
    }  
    

    Randomize the files

    public static class Extensions  
    {  
        private static readonly Random random = new Random();  
      
        public static void Shuffle<T>(this IList<T> list)  
        {  
            int count = list.Count;  
              
            while (count > 1)  
            {  
                count--;  
                  
                int rnd = random.Next(count + 1);  
                  
                T value = list[rnd];  
                list[rnd] = list[count];  
                list[count] = value;  
            }  
        }  
    }  
    

    Get the files

    public class FileOperations  
    {  
          
        public static List<FileItem> GetFilesFromPath(string folderName, string extension = "*.*") =>  
            Directory.GetFiles(folderName, extension).Select(file => new FileItem()  
            {  
                FileName = Path.GetFileName(file),   
                FolderName = folderName  
            }).ToList();  
    }  
    

    Form code which load files into a list then assign to a BindingSource. Once loaded, we select a file then mark it as selected rather than delete it.

    public partial class Form1 : Form  
    {  
        private readonly BindingSource _bindingSource = new BindingSource();  
        public Form1()  
        {  
            InitializeComponent();  
            SelectButton.Enabled = false;  
            label1.Text = "";  
        }  
          
        private void SelectButton_Click(object sender, EventArgs e)  
        {  
            var fileItemsList = ((List<FileItem>) _bindingSource.DataSource);  
              
            fileItemsList.Shuffle();  
              
            var fileItem = fileItemsList.FirstOrDefault(item => item.Selected == false);  
            if (fileItem != null)  
            {  
                fileItem.Selected = true;  
                listBox1.Items.Add(fileItem.FileName);  
            }  
      
      
            var count = fileItemsList.Count(item => item.Selected == false);  
      
            label1.Text = $"{count} not select of {fileItemsList.Count}";  
      
            if (count != 0) return;  
            SelectButton.Enabled = false;  
            LoadButton.Enabled = true;  
      
        }  
      
        private void LoadButton_Click(object sender, EventArgs e)  
        {  
            string folderName = "TODO";  
      
            if (!Directory.Exists(folderName)) return;  
              
            listBox1.Items.Clear();  
            label1.Text = "";  
      
            SelectButton.Enabled = true;  
      
            _bindingSource.DataSource = FileOperations.GetFilesFromPath(folderName);  
      
            LoadButton.Enabled = false;  
        }  
    }  
    

    117684-random.png


1 additional answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2021-07-25T14:09:29.65+00:00

    Try something like this:

    Random rand = new Random( );
    List<string> files = Directory.GetFiles( "Select Directory" ).ToList( );
    if( files.Count > 0 )
    {
        int i = rand.Next( files.Count );
        string randomFile = files[i];
        files.RemoveAt( i );
        // . . .
    }
    
    // next time:
    if( files.Count > 0 )
    {
        int i = rand.Next( files.Count );
        string randomFile = files[i];
        files.RemoveAt( i );
        // . . .
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.