- Home /
How to make/write to files, then read immediately?
I've been having trouble with reading files immediately after I have made them within Javascript. Even when I have done Directory.CreateDirectory(filepath), then check with File.Exists(filepath), it returns false. Is there some kind of refresh function I need to call to refresh the files? I am storing to Application.persistentDataPath.
I have tried methods from this thread:
http://forum.unity3d.com/threads/5084-Can-I-read-and-write-text-files-using-Javascript
but to no avail.
Thanks in advance.
Is there really a need to read from the file immediately after writing it? surely you already have the data accessible since you just used it to write? I'm just curious as to why the extra leg work?
Answer by Bunny83 · Feb 10, 2013 at 05:04 PM
Well, the problem could be that the filehandle isn't released immendiately. In C# you usually out the file object in a using statement. This will invoke the IDisposable interface of the file object and should release the filehandle once you left the using block. I thought that the Close function does the same thing, but i could be wrong.
In C# it would look like this:
// [...]
using(StreamWriter sw = new StreamWriter(filepathIncludingFileName))
{
sw.WriteLine("Line to write");
sw.WriteLine("Another Line");
sw.Flush();
sw.Close();
}
// Here it should be closed and freed.
I'm not sure if UnityScript supports the using block in some way. Since it's a non-standard language it's hard to tell.
edit
In UnityScript it might help when you call Dispose(); manually:
// UnityScript
var sw = new StreamWriter(filepathIncludingFileName)
sw.WriteLine("Line to write");
sw.WriteLine("Another Line");
sw.Flush();
sw.Close();
sw.Dispose();
Thanks for clarifying. Turns out I was being stupid and had some yields going on before creating a root directory, so essentially I was trying to write to files that actually didn't exist. To anyone reading this: watch where you put your yields!