【发布时间】:2018-06-13 20:32:04
【问题描述】:
我正在尝试制作一个 C# 应用程序,该应用程序可以从 .txt 文件读取和输出信息,然后允许用户在该文件末尾输入更多信息。我正在尝试以 CSV 格式编写文本文件,但在弄清楚如何添加到文件的底部时遇到了很多麻烦。似乎当我尝试时,它会覆盖文件的顶行。任何帮助表示赞赏。这是到目前为止的代码,对于任何令人困惑的行,我深表歉意——我一直在尝试许多不同的东西,我可以在网上找到它来尝试让它工作。
class Program
{
static void Main(string[] args)
{
string UIName = "";
string UIInvoice = "";
string UIDue = "";
string UIAmount = "";
using (FileStream fs = new FileStream(@"C:\Accounts.txt", FileMode.Open))
using (StreamReader sr = new StreamReader(fs))
{
string content = sr.ReadToEnd();
string[] lines = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
int lineCount = 0;
List<Account> accounts = new List<Account>();
foreach (string line in lines)
{
string[] column = line.Split(',');
if (lineCount != 0)
{
Account account = new Account();
account.AccountName = column[0];
account.InvoiceDate = column[1];
account.DueDate = column[2];
account.AmountDue = column[3];
accounts.Add(account);
}
lineCount++;
}
Console.WriteLine(content);
}
using (FileStream fs = new FileStream(@"C:\Accounts.txt", FileMode.OpenOrCreate))
using (StreamWriter sw = new StreamWriter(fs))
{
Account account = new Account();
account.AccountName = UIName;
account.InvoiceDate = UIInvoice;
account.DueDate = UIDue;
account.AmountDue = UIAmount;
//accounts.Add(account);
string fullText = (UIName + "," + UIInvoice + "," + UIDue + "," + UIAmount);
Console.WriteLine("Would you like to enter additional data?");
Console.WriteLine("Please enter the Account Name: ");
UIName = Console.ReadLine();
Console.WriteLine("Please enter the Invoice Date: ");
UIInvoice = Console.ReadLine();
Console.WriteLine("Please enter the Due Date: ");
UIDue = Console.ReadLine();
Console.WriteLine("Please enter the AmountDue: ");
UIAmount = Console.ReadLine();
File.AppendAllText("C:/Accounts.txt", fullText + Environment.NewLine);//can't get this way working, even after switching "\"s to "/"s. It says that the file is being used by another process.
Console.ReadLine();
}
}
}
}
单独的类:
public class Account
{
public string AccountName { get; set; }
public string InvoiceDate { get; set; }
public string DueDate { get; set; }
public string AmountDue { get; set; }
public static string GetAccountCSV(Account account)
{
string returnValue = account.AccountName + "," + account.InvoiceDate + "," + account.DueDate + "," + account.AmountDue;
return returnValue;
}
}
.txt 文件说;
Account Name,Invoice Date,Due Date,Amount Due
Jane Doe,1/12/2017,2/12/2017,2000.00
Gonuts Inc,12/31/2017,2/28/2017,1566.50
【问题讨论】:
-
以追加模式打开文件。
new FileStream(@"C:\Accounts.txt", FileMode.OpenOrCreate)应改为new FileStream(@"C:\Accounts.txt", FileMode.Append)
标签: c#