我知道之前曾多次询问过这个问题,但我仍然无法找到原因。我确定该文件不被外部程序使用,因此原因必须是此方法。错误发生在我第二次初始化StreamWriter对象的行中(int for for循环)。
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]);
}
}
}
答案 0 :(得分:2)
完成后,您应该丢弃Stream.Writer。
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
}
}
修改强>
喜欢@enkryptor提到:如果你想在第二个循环中将所有推荐的电影放在你的文件中,你应该在你的循环中使用StreamWriter
而不是。你还应该放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)
}
}