Here is an example with all code in a Form, it would be cleaner though to split up the classes into separate files, this is also recommended by Microsoft.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace TestForm1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonFill_Click(object sender, EventArgs e)
{
BooksHelper.Books = readBookData();
Debug.Print("Total books = " + BooksHelper.Books.Count);
}
private void buttonSave_Click(object sender, EventArgs e)
{
AnotherBookClass.WriteAllBooks("books2.txt");
}
public Queue<Book> readBookData()
{
Queue<Book> books = new Queue<Book>();
StreamReader sr = new StreamReader("Books.txt");
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
string[] words = line.Split(',');
Book bk = new Book();
bk.Author = words[0];
bk.Book_Name = words[1];
bk.Publisher = words[2];
bk.Year = int.Parse(words[3]);
bk.Category = words[4];
books.Enqueue(bk);
}
return books;
}
}
public class Book
{
public string Author { get; set; }
public string Book_Name { get; set; }
public string Publisher { get; set; }
public int Year { get; set; }
public string Category { get; set; }
override public string ToString()
{
return Author + "," + Book_Name + "," + Publisher + "," + Year + "," + Category + Environment.NewLine;
}
}
public static class BooksHelper
{
public static Queue<Book> Books = new Queue<Book>();
}
public static class AnotherBookClass
{
public static void WriteAllBooks(string fileName)
{
foreach (Book item in BooksHelper.Books)
{
File.AppendAllText(fileName, item.ToString());
}
}
}
}