This recipe illustrates how to use C# streams to write text data to a text file, either into the standalone project's Data
folder or to the Resources
folder.
In the 0423_08_02
folder, we have provided the FileReadWriteManager.cs
class script file:
To save external text files using C# file streams, follow these steps:
FileReadWriteManager.cs
into your project.// file: SaveTextFile.cs using UnityEngine; using System.Collections; using System.IO; public class SaveTextFile : MonoBehaviour { public string fileName = "hello.txt"; public string folderName = "Data"; private string filePath = "(no file path yet)"; private string message = "(trying to save data)"; private FileReadWriteManager fileManager; void Start () { fileManager = new FileReadWriteManager(); filePath = Application.dataPath + Path.DirectorySeparatorChar + fileName; string textData = "hello and goodbye"; fileManager.WriteTextFile( filePath, textData ); message = "file should have been written now ..."; } void OnGUI() { GUILayout.Label("filepath = " + filePath); GUILayout.Label("message = " + message); } }
hello.txt
in the Data
folder of your project's standalone files, containing the lines "hello" and " and goodbye".When the game runs, the Start()
method creates the filePath
string from the public variables fileName
and folderName
, and then calls the WriteTextFile()
method from the fileReadWriteManager
object, to which it passes the filePath
and textData
strings. This method creates (or overwrites) a text file (for the given file path and filename) containing the string data received.
Some details you don't want to miss:
Standalone build applications contain both a Data
folder and a Resources
folder. Either of these can be used for writing (or some other folder, if desired). We generally put read-only files into the Resources
folder and use the Data
folder for files that are to be created from scratch or have had their contents changed.
18.189.178.53