【C#】书籍信息的添加、修改、查询、删除
using System;
using System.IO;
namespace pages_211_编程题3_2_书籍信息的查看与编辑
{
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public DateTime PublishDate { get; set; }
public decimal Price { get; set; }
public Book() { }
public Book(string title, string author, string publisher, DateTime publishDate, decimal price)
{
Title = title;
Author = author;
Publisher = publisher;
PublishDate = publishDate;
Price = price;
}
public void SaveToFile(string filePath)
{
File.WriteAllText(filePath, $"书名: {Title}\n作者:{Author}\n出版社: {Publisher}\n出版日期: {PublishDate}\n定价: {Price}");
}
public static Book LoadFromFile(string filePath)
{
string[] lines = File.ReadAllLines(filePath);
return new Book
{
Title = lines[0].Split(new char[] { ':' }, 2)[1].Trim(),
Author = lines[1].Split(new char[] { ':' }, 2)[1].Trim(),
Publisher = lines[2].Split(new char[] { ':' }, 2)[1].Trim(),
PublishDate = DateTime.Parse(lines[3].Split(new char[] { ':' }, 2)[1].Trim()),
Price = decimal.Parse(lines[4].Split(new char[] { ':' }, 2)[1].Trim())
};
}
public static void DeleteBookFile(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
Console.WriteLine("书籍文件删除成功。");
}
else
{
Console.WriteLine("书籍文件不存在。");
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Title = "书籍管理器";
bool exit = false;
while (!exit)
{
Console.WriteLine("\n书籍管理器");
Console.WriteLine("1. 添加/编辑书籍");
Console.WriteLine("2. 查看书籍");
Console.WriteLine("3. 删除书籍");
Console.WriteLine("4. 退出");
Console.Write("请选择一个选项:");
int option = Convert.ToInt32(Console.ReadLine());
switch (option)
{
case 1:
AddEditBook();
break;
case 2:
ViewBook();
break;
case 3:
DeleteBook();
break;
case 4:
exit = true;
break;
default:
Console.WriteLine("选项无效,请再试一次");
break;
}
}
}
static void AddEditBook()
{
Console.Write("请输入书名:");
string title = Console.ReadLine();
Console.Write("请输入作者:");
string author = Console.ReadLine();
Console.Write("请输入出版社:");
string publisher = Console.ReadLine();
Console.Write("请输入出版日期(格式为yyyy-MM-dd):");
DateTime publishDate = DateTime.Parse(Console.ReadLine());
Console.Write("请输入定价:");
decimal price = decimal.Parse(Console.ReadLine());
Book book = new Book(title, author, publisher, publishDate, price);
Console.Write("请输入保存书籍的文件路径:");
string filePath = Console.ReadLine();
book.SaveToFile(filePath);
Console.WriteLine("书籍保存成功。");
}
static void ViewBook()
{
Console.Write("请输入要查看书籍的文件路径:");
string filePath = Console.ReadLine();
Book book = Book.LoadFromFile(filePath);
Console.WriteLine($"书名: {book.Title}");
Console.WriteLine($"作者: {book.Author}");
Console.WriteLine($"出版社: {book.Publisher}");
Console.WriteLine($"出版日期: {book.PublishDate.ToShortDateString()}");
Console.WriteLine($"定价: {book.Price}");
}
static void DeleteBook()
{
Console.Write("请输入要删除书籍的文件路径:");
string filePath = Console.ReadLine();
Book.DeleteBookFile(filePath);
}
}
}