2013-03-05 43 views
0

(Books类是在此代码之外定义的。)所以当我尝试从该文件读取一本书时,我只得到这本书。每当我添加一个新的老版本时,它都会被写下来。所以我无法将新书添加到我的myLibraryBooks列表中,因为它会被自动覆盖。当我尝试写入列表时,我的上一个文本被覆盖

Books book = new Books(); 

Console.Write("Enter Author Name:"); 
book.Author = Console.ReadLine(); 

Console.Write("Enter Book Title:"); 
book.Title = Console.ReadLine(); 

Console.Write("Enter Book ISBN:"); 
book.ISBN = Console.ReadLine(); 

Console.Write("Enter the Publish Date:"); 
book.Publish_Date = Console.ReadLine(); 

myLibraryBooks.Add(new Books() { Author = book.Author.ToUpper(), Title = book.Title.ToUpper(), ISBN = book.ISBN, Publish_Date = book.Publish_Date.ToUpper() }); 
Console.WriteLine("Book added Successfully"); 
sw.Write(book.Author, FILE_PATH); 
sw.Write("\r\n", FILE_PATH); 
sw.Write(book.Title.ToUpper(), FILE_PATH); 
sw.Write("\r\n", FILE_PATH); 
sw.Write(book.ISBN.ToUpper(), FILE_PATH); 
sw.Write("\r\n", FILE_PATH); 
sw.Write(book.Publish_Date.ToUpper(), FILE_PATH); 
sw.Write("\r\n", FILE_PATH); 
sw.WriteLine(book.Author, FILE_PATH); 
sw.Close(); 
+0

你在哪里看到这个代码中的问题?你是说“foreach”只发生一次,你期望它多次? – 2013-03-05 20:25:03

+0

当我尝试向我的文件添加一本书时,它会覆盖当前在那里的书。 – 2013-03-05 20:26:45

+0

你能显示声明和'sw'的开头吗?这里缺少一些东西。 – Steve 2013-03-05 20:33:47

回答

3

我在这里假设很多,但我想尝试给出一个答案。

如果sw是一个StreamWriter(我不能看到声明),那么你应该

using(StreamWriter sw = new StreamWriter("yourFile", true)) 

打开它迫使StreamWriter的追加到当前的数据,而不是将其覆盖

See MSDN StreamWriter constructors

还有sw.Write呼叫是错误的。您正在使用带格式字符串的重载和要插入格式字符串的对象。相反,您只需编写书籍的属性即可。

您应该使用

sw.WriteLine(book.Author); 

有一个单独的行每个属性,而不是在一个行togheter贴。

+0

+1表示没有OP发布代码,甚至没有明确的问题。 -1到OP没有阅读文档和提供错误的示例代码.......... – 2013-03-05 20:29:47

+0

@Steve它是从这段代码中声明的。 – 2013-03-05 20:32:13

相关问题