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);
}
}
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).