[C#] StreamWriter throwing Sharing Violation on path
I'm currently writing code for a game on Unity using C#. For whatever reason, I keep getting sharing violations when I try to create a StreamWriter to write out to a file. The file already exists and isn't open in another text editor, since I've seen that can cause issues. Earlier in the same code, I do open a StreamReader, but I've tried removing the StreamReader from the code and I still get the error, while the StreamReader functions without issue. I've also tried moving the StreamWriter section of the code to a different object just to try, but that hasn't changed it either.
The code involved is just
StreamWriter output = new StreamWriter("record.txt"); foreach(int el in Level.scores) { output.WriteLine(el); } output.Dispose();
And I get an error on the first line. For reference, the section is supposed to be part of a record file that I use to keep track of the top 5 scores in the game. The code in question is supposed to read from the file the current scores, compare the scores to the one that the player has just made, and then write the scores back to the file. The reading and comparing isn't the issue, that gets by fine, but the writing isn't working.
Which OS? And what would be the absolute path you're writing to?
As it's probably Windows, you can't assume to have write access to the program directory. Use Application.persistentDataPath,
I'm using Windows, yeah. How would I use that to solve the issue, sorry? I've not really used C# before this, learned it through program$$anonymous$$g this essentially.
If that is indeed the problem (which i don't know for sure), you need to find a directory where you have write permission. Application.persistentDataPath points to a directory specific to the current user and application. $$anonymous$$g.
"C:/Users/USERNA$$anonymous$$E/AppData/LocalLow/DefaultCompany/project name"
So, ins$$anonymous$$d of
StreamWriter("record.txt");
try
StreamWriter( Application.persistentDataPath + "/record.txt");
Your answer
Follow this Question
Related Questions
How to declare a list of arrays? 1 Answer
I want my script to wait 2 seconds before continue in a condition, in update, using C# 2 Answers
Problems with scripting and invokeRepeating 1 Answer
OnCollisonEnter2D Not Firing after checking collider 1 Answer
error CS0120: An object reference is required to access non-static member 1 Answer