text-file writing IOException: Sharing violation on path

hi all.
i have a .txt-file which is created by a second program
with unity i want to change some lines of my .txt-file but i always get the IOexception error.
dunno whats wrong with my code. tried to google a solution and found different ways of dealing with my problem, but none worked so far.

using UnityEngine;
using System.IO;

public class txtExportieren : MonoBehaviour
{


    StreamWriter writer;
    StreamReader reader;

    string path = "O:/PO/Ablage/13_BEI/Florian Pollok/PlantSocket/asd.txt";

    public Vector3 pos;
    GameObject[] cubesArray;

    public void Button_export()
    {
        writer = new StreamWriter(path, false)

        cubesArray = GameObject.FindGameObjectsWithTag("Plant");

        foreach (GameObject Plant in cubesArray)
        {

            reader = new StreamReader(path);

            pos = Plant.transform.position;
            var ANAME = Plant.name;
            var AX = Mathf.Round(pos[0]);
            var AZ = Mathf.Round(pos[2]);

            for (var path = reader.ReadLine(); path != null; path = reader.ReadLine())
            {
                var items = path.Split('    ');
                string itemLabel = items[0];

                if (items[0] == ANAME)
                {
                    writer.WriteLine(items[0] + '    ' + AX + '    ' + AZ + '    ' + items[3]);

                }
                reader.Dispose();
                writer.Dispose();
                writer.Close();
                reader.Close();
            }


        }

    }

}

greetz

I’ll admit it’s been awhile since I’ve used a StreamReader or StreamWriter class, but one thing I do recall is it’s better to use the Using format of it. StreamWriter Class (System.IO) | Microsoft Learn

There is also the File.ReadAllLines which returns an array of strings and you can loop through it, which is what I tend to use…now, that being said…

I haven’t used Dispose and Close when I did use StreamReader/Writer since the using takes care of that. But you appear to have dispose and close inside your loop, which means you’re doing that each loop. I don’t think this is correct. I believe you need to do that outside your loop. But honestly, I would switch to the using version of your streamwriter/reader

1 Like

You could try \ instead of / in your path - although both should work. Also try doing a try/catch around the StreamWriter create to get more detailed info on the exception.

e.g. use catch (Exception ex) and output ex.Message