IOException: Sharing violation on path ...

I’m trying to create a file if it doesn’t exists.The file gets created but the first time I run this script it throws an error: “IOException: Sharing violation on path…”. What is causing this?
It only throws an error the first time the script is running, when the file exists no errors are thrown.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;

public class LogSystem : MonoBehaviour {

    private static string logFilename;
    private static string filepath;

    public static LogSystem instance;
    private string fulldate;

    private void Awake()
    {
        if (instance == null)
            instance = this;
        else if (instance != this)
            Destroy(gameObject);

        DontDestroyOnLoad(gameObject);
    }

    private void Start()
    {
        string month = System.DateTime.Now.Month.ToString();
        string day = System.DateTime.Now.Day.ToString();
        string year = System.DateTime.Now.Year.ToString();

        fulldate = year + month + day;

        logFilename = "LOG_" + fulldate + ".txt";
        filepath = Path.Combine(Application.streamingAssetsPath + "/Logs/", logFilename);

        if (!File.Exists(filepath))
            File.Create(filepath);

        WriteToLog("Log Entry");
    }

    public static void WriteToLog(string logMessage)
    {
        string outputString = System.DateTime.Now.ToString() + ":    " + logMessage + Environment.NewLine;
        string filetext = File.ReadAllText(filepath) + Environment.NewLine;

        File.WriteAllText(filepath, outputString + filetext);
    }

}

Did you google the error?
http://answers.unity3d.com/questions/990496/ioexception-sharing-violation-on-path-please-help.html

1 Like

File.Create returns a FileStream. The documentation states that the default sharing option is set to none, i.e. you have to close the file to make it available for other parts of your code (in this case, the subsequent write operation).

Thank you… I did however google it, but none of the hundreds of result told me that I need to add .Dispose() :slight_smile: