Some C# methods to write and read files, creating a folder and listing files inside it



This two C# snippets may be useful to you if you are working on file read and write in your Unity C# project.

Don’t forge to use System.io okay?

Here is the code:

Write to file

public void WriteToFile()
{
	string targetfolder = Application.persistentDataPath + "/somefolder/";
	
	if (!Directory.Exists(targetfolder))
	{
		Directory.CreateDirectory(targetfolder);
	}
	
	string FILE_PATH = targetfolder + "myfile.txt";

	StreamWriter sr = File.CreateText(FILE_PATH);
	sr.WriteLine("Some Text");
	sr.Close();

	//This line bellow is for reading file
	//Debug.Log("Reading: " + File.ReadAllText(targetfolder + "myfile.txt"));

}

List files inside a directory

public void ListFiles()
{
	string targetfolder = Application.persistentDataPath + "/somefolder/";
	DirectoryInfo d = new DirectoryInfo(targetfolder);
	FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
	string str = "";

	foreach (FileInfo file in Files)
	{
		str += "File found: " + file.Name;
	}

	Debug.Log(str);
}

List directories inside a directory ordered by date

DirectoryInfo di = new DirectoryInfo(targetfolder);  //targetfolder is a string of your target directory that you want to list its subfolders
            DirectoryInfo[] diArray = di.GetDirectories();
            Array.Sort(diArray, (y, x) => StringComparer.OrdinalIgnoreCase.Compare(x.CreationTime, y.CreationTime));
            foreach (DirectoryInfo fi in diArray)
            {
                //Do your things here
            }
loading...

Leave a Reply

Your email address will not be published.