-1

I have a big problem with my code i allways get a IO Exception and i don´t know why... I use a StreamWriter...

    internal void SaveOwner(Owner o)
    {
        StreamWriter w = new StreamWriter(path, true);
        if (o != null)
            w.WriteLine(o.ToFileString());
        w.Close();
    }

Pleace can anyone help me i don´t konw i have tried everything what i konw..!? It allways says that a other process use the file. IO Exception - file used by another process Befor i call the Method i asked if o != null

the code is in C#

2 Answers2

0

You should wrap your calls within using blocks so that the object is disposed of at a proper time.

internal void SaveOwner(Owner o)
{
    using(StreamWriter w = new StreamWriter(path, true))
    {
       if (o != null)
       {
          w.WriteLine(o.ToFileString());
       }
    }
}
Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24
  • `Close` calls `Dispose`. I agree it looks better, but that is not the issue here. – Bauss Aug 21 '15 at 11:39
  • well `close` does call `dispose` , but a `using` block ensures it is done the proper way it should. – Amit Kumar Ghosh Aug 21 '15 at 11:41
  • The issue is most likely a multi-threading issue, rather than the actual stream itself. Reproduced his problem: http://prntscr.com/876z74 – Bauss Aug 21 '15 at 11:47
0

I believe this is caused because of multi-threading due to that I was able to reproduce your issue by that.

Thrown Exception

You can simply wrap a lock (Use a static object.) and for goodness sake use the using keyword to wrap your stream.

static object syncRoot = "";

...

void SaveOwner(Owner o)
{
    lock (syncRoot)
    {
        using (StreamWriter w = new StreamWriter(path, true))
        {
            if (o != null)
                w.WriteLine(o.ToFileString());
        }
    }
}
Bauss
  • 2,767
  • 24
  • 28