Stream Writer Help

I have this code:

import System.IO;
private var fileName = "Savefile.txt";
private var words : String[];

    function Start () {
        var sr = new StreamReader(Application.dataPath + "/" + fileName);
        var fileContents = sr.ReadToEnd();
    	words = fileContents.Split("

"[0]);
}

    function Update () {
    
    if (Input.GetKeyDown (KeyCode.R)) {
        var sw = new StreamWriter(Application.dataPath + "/" + fileName);
       	sw.Write ("testingagain");  
    }
    
    }

I’ve encountered two problems:
I press R several times and it comes up with the Sharing Violation Error.
My second problem is that it erases everything in the text file and doesn’t write ‘testingagain’.
How do I fix both problems and get it so that I can choose specific lines to write on in the text file.
Much would be appreciated.

Your update function needs to be changed to look like this:

    function Update () {
 
	    if (Input.GetKeyDown (KeyCode.R)) {
	        var sw = new StreamWriter(Application.dataPath + "/" + fileName,true);
	        sw.Write ("testingagain"); 
	        sw.Close();
	    }
 
    }

You are getting the error every time because you are not closing the Streamwriter. Also you need to flag true as the second parameter for the stream writer constructor to signify that you want to append.
You need to call Close() or Flush() if you want to write from buffer to file. Since you are creating a new streamwriter every time you press R I have put a Close() call in for you.

You forgot to close StreamReader & StreamWriter:

function Start ()
 {
     var sr = new StreamReader(Application.dataPath + "/" + fileName);
     var fileContents = sr.ReadToEnd();
     words = fileContents.Split("

"[0]);
sr.Close(); //Here
}

 function Update () {
 
 if (Input.GetKeyDown (KeyCode.R))
 {
     var sw = new StreamWriter(Application.dataPath + "/" + fileName);
     sw.Write ("testingagain"); 
     sw.Close();   // And here
 }