I have a stream reader I am using to parse data into a program. When I first open the scene from the main menu, the stream reader works correctly in parsing the data (I omitted the parse in my snippet as the code is long). The text.text output to the screen on the first run is G. If I go load back to the main menu, and then back into this scene however the text.text output is the first line of the text document where my code reads text.text = line and I am trying to figure out why. Is sr.Close() not the proper way to close the stream reader? Or is the file somehow still open?
void Start () {
text.text = "A";
trimAndPlaceDataSets = GetComponent<TrimAndPlaceDataSets> ();
text.text = "B";
string AthenaData = Application.streamingAssetsPath + "/Athena.txt";
text.text = "C";
PopulateAthenaData(AthenaData);
}
void PopulateAthenaData(string s){
text.text = "D";
using (StreamReader sr = new StreamReader(s)) {
text.text = "E";
string line = sr.ReadLine();
text.text = line;
while (line != null) {
//Do Stuf
sr.ReadLine();
}
sr.Close();
text.text = "G";
}
}
And this is how I am loading my scenes
public void LoadPressed() {
scenesDropdown.gameObject.SetActive(false);
loadButton.SetActive(false);
SceneManager.LoadScene(scenesArray[scenesDropdown.value]);
}
Your problem is about "Garbage Collection" (visit this Url : "https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/") Simple answer is C# can release (dispose) lots of things after you using them but somethings like "files" aren't one of them. You have to release them after using and if you don't that, your file will be open and another process can't access that. You need to dispose "StreamReader" after your work is done. And "using" do that (you don't need to write a custom disposer for that).
using (StreamReader sr = new StreamReader("Your file path"))
{
//do your work
}
after that, file will be released automatically.