Create Text File

I am trying to create an example of Unity creating Text files / directories. Can someone point to me the correct function I need to call to have unity create a new file called “Data” or something?

This tool is meant to take a number of GUI textfields, be saved, and then loaded for later use. so simple Text files on the local harddrive is all I need.

Code I have:

var firstnameGUI : First Name;
var lastnameGUI : Surname;

function OnGUI () {
    firstnameGUI = GUI.TextField (Rect (25, 80, 150, 30), firstnameGUI);
    lastnameGUI = GUI.TextField (Rect (25, 115, 150, 30), lastnameGUI);

if (GUI.Button (Rect (25, 350, 120, 30), "Save User")) {

    //create Username

    usernameGUI = firstnameGUI.Substring(0,1) + lastnameGUI.Substring(0,1);

    //create Folder
    if (!Directory.Exists ("C:/Data/" + usernameGUI)) {

        Directory.CreateDirectory ("C:/Data/" + usernameGUI);
    }
    //Create Text file.. but dont know how.. How to create the Text file to save to.
    //save to textfile

       File.WriteAllText(firstnameGUI, lastnameGUI);
    }

}

You’re very close. :slight_smile:

File.WriteAllText does take two arguments like you’ve supplied, but the first one is the filepath. The text you want to write is the second one. So you need something like,

System.IO.File.WriteAllText("C:\blahblah_yourfilepath\yourtextfile.txt", firstnameGUI + ", " + lastnameGUI);

That is, assuming you want your values comma-separated in the file. You can format the string that gets written in whatever way you like.

You try with this it works…

System.Text.UnicodeEncoding encod = new System.Text.UnicodeEncoding();
byte byteData = encod.GetBytes(Downloadchat);

			System.IO.FileStream oFileStream = null;
			oFileStream = new System.IO.FileStream("D:\\chats.txt", System.IO.FileMode.Create);
			oFileStream.Write(byteData, 0, byteData.Length);
			oFileStream.Close ();

Doesnt work for me.? I get an error:

unexpected char: ‘U’.

When I do

System.IO.File.WriteAllText("C:\Users\Simon\Desktop\exampleSaveData.txt", stringToPost);

I have no clue why its erroring on the first letter of the first folder in the path string…?? I tried rebooting Unity but I get the same error… Am I going mad??