Questions And Answers

More Tutorials

Select random file from directory in C#

To select random file from directory in C# first we need to get list of file info objects using directoryInfo.GetFiles() method then we create a random number between 0 and number of files, finally we use that random integer to select a file from the list of files info.

Remember to include all required namespaces: using System;, using System.IO;, using System.Linq;

Example of selecting random file in C#

using System;
using System.IO;
using System.Linq;

public class Program
	public static void Main()
		var directoryInfo = new DirectoryInfo(@"C:\Path_To_Folder");
		var listFileInfo = directoryInfo.GetFiles("*.*");
		Random random = new Random();
		string randomFile = listFileInfo.ElementAt(random.Next(0, listFileInfo.Length)).FullName;


In this page (written and validated by ) you learned about Select random file from directory in C# . What's Next? If you are interested in completing C# tutorial, we encourage you simply to start here: C# Tutorial.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.