Share Violation and Object reference not set issue

Hello Members,

While developing Logger into my Monodevelop tool when i run it I am getting two errors,

  1. Sharing violation on path
  2. NullReferenceException: Object reference not set to an instance of an object

Here is the code snippet…which i have written

if(!(File.Exists("D:\\Log\log.txt")))
{

    File.Create("D:\\Log\log.txt");

}

try {

    fs = new FileStream ("D:\\Log\log.txt", FileMode.Append, FileAccess.Write, FileShare.None);
		
    streamWriter = new StreamWriter (fs);
    streamWriter.WriteLine ("Header");
    streamWriter.Flush ();

} catch (Exception ex) {
    UnityEngine.Debug.Log ("Exception in creating Log File" + ex.ToString ());
}

Even if I change the FileShare.None to FileShare.ReadWrite, I get the same issue.
I am logged in the system as Admin and have full permissions also.
Please guide me how to resolve this issue.
Help will be highly appreciated.

Thanks & regards,
Anoop.

Streams are disposables, you have to dispose a stream after using it - otherwise, you’ll end up having the file opened two times with read and write access.

I would suggest storing the file stream - it will cost to much time opening it for every new line.
You can call myStream.Dispose() or use a using statement:

using(var fileStream = new FileStream("log.txt", FileMode.OpenOrCreate, FileAccess.Write) {
    // Do something with the stream, will get disposed when leaving
    // the scope
}