我正在尝试制作一个 Stream Writer,然后将一些输入从控制台写入文件,然后读出内容。唯一的问题是我想用两种不同的方法来做。从这里写:从这里addbook()
读:list_books()
。但是我无法从该文件中读取,因为流阅读器不允许我访问我的任何变量或该文件以再次使用。
//So I am trying to write from the static void addbook method and then read from the static void list_books method
//I want to Write from one static void and then I want to read them from a different method.
static void addbook()
{
//Here is where I get my strings that I will write
Console.Write("Book Title:");
string title = Console.ReadLine();
Console.Write("ISBN#:");
string isbn = Console.ReadLine();
Console.Write("Author:");
string author = Console.ReadLine();
Console.Write("Publish Date:");
string publish_date = Console.ReadLine();
//Here Is where I create the Stream Reader and Writer
//And where I write to the file
var fs = File.Open("Librarybooks.txt", FileMode.OpenOrCreate,FileAccess.ReadWrite);
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);
sw.WriteLine(title.ToCharArray());
sw.WriteLine(isbn.ToCharArray());
sw.WriteLine(author.ToCharArray());
sw.WriteLine(publish_date.ToCharArray());
Console.WriteLine("Book added Successfully!!");
}
static void list_books()
{
//Here is where I want to read from so I can just call the list_books method.
//But I can't access the StreamReader or StreamWriter
//I just want to be able to read from the file.
}