使用 StreamWriter 将结构写入文本文件
本文关键字:文本 文件 结构 StreamWriter 使用 | 更新日期: 2024-10-30 11:25:06
下面是一个函数,它应该向用户提问,无论用户输入什么,都应该保存到文本文件中。
它是一个结构,应该接受 1 int
、4 strings
和一个DateTime
。到目前为止,这就是我的函数的样子,但它显然不起作用。控制台正在显示问题,但未保存到文本文件中。
static void AddNew(CustomerStruct[] _NewCustomer)
{
Console.Clear();
using (StreamWriter sw = new StreamWriter(@"..'..'..'Files'Customer.txt", true))
{
Console.Write("'n'n Enter Customer Number: ");
sw.WriteLine(_NewCustomer[RecCount].CustomerNo);
Console.Write("'n'n Enter Customer Surname: ");
sw.WriteLine(_NewCustomer[RecCount].Surname);
Console.Write("'n'n Enter Customer Forname: ");
sw.WriteLine(_NewCustomer[RecCount].Forename);
Console.Write("'n'n Enter Customer Street address: ");
sw.WriteLine(_NewCustomer[RecCount].Street);
Console.Write("'n'n Enter Customer Town: ");
sw.WriteLine(_NewCustomer[RecCount].Town);
Console.Write("'n'n Enter Customer DOB: ");
sw.WriteLine(_NewCustomer[RecCount].DOB);
RecCount++;
}
Console.ReadLine();
}
如果你喜欢shorcuts
。static void AddNew(CustomerStruct[] _NewCustomer)
{
Console.Clear();
using (StreamWriter sw = new StreamWriter(@"..'..'..'Files'Customer.txt", true))
{
Console.Write("'n'n Enter Customer Number: ");
sw.WriteLine(_NewCustomer[RecCount].CustomerNo=Console.ReadLine());
Console.Write("'n'n Enter Customer Surname: ");
sw.WriteLine(_NewCustomer[RecCount].Surname=Console.ReadLine());
Console.Write("'n'n Enter Customer Forname: ");
sw.WriteLine(_NewCustomer[RecCount].Forename=Console.ReadLine());
Console.Write("'n'n Enter Customer Street address: ");
sw.WriteLine(_NewCustomer[RecCount].Street=Console.ReadLine());
Console.Write("'n'n Enter Customer Town: ");
sw.WriteLine(_NewCustomer[RecCount].Town=Console.ReadLine());
Console.Write("'n'n Enter Customer DOB: ");
sw.WriteLine(_NewCustomer[RecCount].DOB=Console.ReadLine());
RecCount++;
}
Console.ReadLine();
}
正如您在评论中提到的,您只需要文件中来自控制台的数据。因此,这是"如何从控制台读取数据并将其放入文件中?
您希望从控制台读取数据,然后将其写入流:
public static void ReadNewCustomerFromConsole()
{
var pathToYourFile = @"..'..'..'Files'Customer.txt";
using (var writer = new StreamWriter(pathToYourFile , true))
{
Console.Clear();
// Write a message in Console
Console.WriteLine("Enter Customer Number: ");
// Read user input from Console
var customerNumber = Console.ReadLine();
// Write user input to file
writer.WriteLine(customerNumber);
// Now read Customer Surname
Console.WriteLine("Enter Customer Surname:");
var customerSurname = Console.ReadLine();
writer.WriteLine(customerSurname);
// And so on for the other data you need ...
}
}
请注意,我使用Console.WriteLine()
而不是包含'n
。
另外,如果您真的不想用读取信息填充它,我建议您将您的方法重命名为 ReadNewCustomerFromConsole()
之类的名称,并且不要在其中传递struct
数组(如果您这样做,我建议您使用 class
而不是 struct
)。