In: Computer Science
Create a C# application for Library that allows you to enter data for books and saves the data to a file named Books.txt. Create a Book class that contains fields for title, author, number of pages, and price of the book and ToString() method. The fields of records in the file are separated with asterisk (*). Expecting sentinel value for ending the process of writing to file is "000"
Application Name :LibraryDemo
Application type :Console Application
Language used:C#
IDE used :Visual Studio 2019
Program.cs :
//namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
//application namespace
namespace LibraryDemo
{
class Program //C# class
{
//Main() method
static void Main(string[] args)
{
//creating object of
StreamWriter streamWriter = new StreamWriter("Books.txt");
//Creating obejct of Book class
Book book = new Book();
while (true)
{
//asking user book title
Console.Write("Enter book title: ");
//reading book title
string bookTitle = Console.ReadLine();
//checking boomTitle
if (bookTitle == "000")
{
//when book title is 000 then break while loop
Console.WriteLine("Books written to the file.");
break;
}
else
{
book.Title = bookTitle;
//asking user book author
Console.Write("Enter book author: ");
//reading book author
book.Author = Console.ReadLine();
//asking user number of pages
Console.Write("Enter number of pages: ");
//reading number of pages
book.NumberOfPages = int.Parse(Console.ReadLine());
//asking user price
Console.Write("Enter book price: ");
//reading book price
book.Price = double.Parse(Console.ReadLine());
//call toString() method on Book and write to the file
streamWriter.WriteLine(book.ToString());
}
}
streamWriter.Close();//close streamWriter
//to hold the screen
Console.ReadKey();
}
}
//C# Book class
class Book
{
private string title;
private string author;
private int numberOfPages;
private double price;
//getter and setter methods
public string Title
{
get { return title; }
set
{
this.title = value;
}
}
public string Author
{
get { return author; }
set
{
this.author = value;
}
}
public int NumberOfPages
{
get { return numberOfPages; }
set
{
this.numberOfPages = value;
}
}
public double Price
{
get { return price; }
set
{
this.price = value;
}
}
//method ToString()
public string ToString()
{
return title + "*" + author + "*" + numberOfPages.ToString() + "*"
+ price.ToString();
}
}
}
==============================================
Screen showing output :
Screen showing books.txt :