Sharing violation on path

Hey,

I am creating a file, where I can store the game quality settings.

Here is the code:

function Start()
{
	readConfig();
}

function OnGUI()
{
	//Lots of code
	
	if (GUI.Button(Rect (150, 640, 150, 50), "Back", myStyle))
	{
		playSound();
		UpdateConfig();
		readConfig();
		SetResolution();
	}
	
	//Lots of code
}

function readConfig()
{
	var ind : int = 0;
	sr = new File.OpenText(configPath);
	input = "";

	while (true)
	{
		input = sr.ReadLine();
		if (input == null) 
		{
			break;
		}
		config.Push(input);
	}
	
	audioVolume = parseInt(config[5]);
	musicVolume = parseInt(config[6]);
	
	SetResolution();
}

function SetResolution()
{
	var res 	: int = parseInt(config[2]);
	var full 	: int = parseInt(config[3]);
	
	var isFull	: boolean;
	
	switch (full)
	{
		case 0:
			isFull = false;
			break;
		
		case 1:
			isFull = true;
			break;
			
		default:
			break;
	}
	
	switch (res)
	{
		case 0:
			Screen.SetResolution (800, 600, isFull);
			break;
			
		case 1:
			Screen.SetResolution (1024, 768, isFull);
			break;
			
		case 2:
			Screen.SetResolution (1280, 768, isFull);
			break;
			
		case 3:
			Screen.SetResolution (1366, 768, isFull);
			break;
		
		default:
			break;
	}
	
	QualitySettings.currentLevel = QualityLevel.Fantastic;
	
}

function UpdateConfig()
{
	var sw : StreamWriter = new StreamWriter(configPath);
	for (var i = 0; i < config.length; i++)
	{
		sw.WriteLine(config*);*
  • }*
  • sw.Flush();*
  • sw.Close();*
    }
    The problem is, when I click on the back button, I get a “IOException: Sharing violation on path D:\Unity\Marble Worlds 2\Marble Worlds\config.txt”.
    The file is created succesfully by another script, and it is there. Also, when I make a build from the game, the file is not rewrited. It writes new lines to the end of the file, rather than deleting the previous lines, and write the new line’s to their place.
    What is wrong with the code?
    Thanks for your help.

Should probably Close sr in readConfig. That would cause an error when you tried to open to write it (can’t write to a file if someone is reading.)

new StreamWriter(...) often has an optional 2nd input specifying Append (write to end) or write from start. The default is usually to erase and rewrite, but maybe not in unityScript.

How to make a file and write to it in the same function, without getting the file share violation error. (I’m not sure if this is what Owen Reynolds meant, maybe i’m just saying the same thing)

StreamWriter sw = System.IO.File.CreateText("path");
sw.Close();
System.IO.File.WriteAllText("path", "text");