PoVa PoVa - 1 month ago 7
C# Question

The process cannot access the file 'file path' because it is being used by another process

I know this has been asked multiple times before but I still can't find what's the cause of this. I'm sure the file isn't being used by an external program, so the cause must be in this method. The error occurs in the line where I initialize StreamWriter object for the second time (int the for loop).

static void WriteData(PeopleContainer people)
{
var file = new StreamWriter(File.Open(Directory + Output1, FileMode.Create), Encoding.GetEncoding(1257));
for (int i = 0; i < people.SeenByEveryone.Count; i++)
{
Film film = people.SeenByEveryone.GetFilm(i);
file.WriteLine("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}", CsvSeparator, film.Title, film.Year,
film.Director, film.Genre, film.Company, film.BoxOffice, film.Actors[0], film.Actors[1]);
}

for (int i = 0; i < people.Count; i++)
{
Person person = people.GetPerson(i);
string path = String.Format("{0}Rekomendcija_{1}_{2}.csv", Directory, person.FirstName, person.LastName);

file = new StreamWriter(File.Open(path, FileMode.Create), Encoding.GetEncoding(1257));
for (int j = 0; j < person.RecomemdedFilms.Count; j++)
{
Film film = person.RecomemdedFilms.GetFilm(j);
file.WriteLine("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}{6}{0}{7}{0}{8}", CsvSeparator, film.Title, film.Year,
film.Director, film.Genre, film.Company, film.BoxOffice, film.Actors[0], film.Actors[1]);
}
}
}

Answer

You should dispose your Stream.Writer when you are finished with it.

        using(var file = new StreamWriter(File.Open(Directory + Output1, FileMode.Create), Encoding.GetEncoding(1257)))
        {
            //your loop
        }

        for (int i = 0; i < people.Count; i++)
        {

            using(file = new StreamWriter(File.Open(path, FileMode.Create), Encoding.GetEncoding(1257)))
            {
                 // other loop
            }
        }

EDIT:

Like @enkryptor mention: if you want all the recommended films to be in your file in the second loop, you should use StreamWriter not in your loop. Also you should put FileMode.OpenOrCreate

using(file = new StreamWriter(File.Open(path, FileMode.OpenOrCreate), Encoding.GetEncoding(1257)))
{
    for (int i = 0; i < people.Count; i++)
    {

          file.WriteLine(...//your stuff)         
    }
}
Comments