我正在尝试创建一个csv文件,其中每个条目都由用户输入。一旦输入了一组值,它就应该继续下一个。但是我似乎无法做到这一点。每次运行程序时,它都会替换以前的值。
using System;
using System.IO;
using System.Collections.Generic;
namespace FileAccess
{
class MainClass
{
public static void Main(string[] args)
{
string FName;
string LName;
string Dpt;
string Grade;
string NumberOfHours;
string file_name = "EmployeeDetails.txt";
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(file_name);
String[] ArrayDetails = new string[5];
Console.Write("Enter Emp First Name: ");
FName=Console.ReadLine();
Console.Write("Enter Emp Last Name: ");
LName = Console.ReadLine();
Console.Write("Enter Emp Department: ");
Dpt = Console.ReadLine();
Console.Write("Enter Employee Grade: ");
Grade = Console.ReadLine();
Console.Write("Enter Number Of Hours Worked: ");
NumberOfHours = Console.ReadLine();
ArrayDetails[0] = FName;
ArrayDetails[1] = LName;
ArrayDetails[2] = Dpt;
ArrayDetails[3] = Grade;
ArrayDetails[4] = NumberOfHours;
// Create new list of strings
List<string> LDetails = new List<string>(); // Create new list of strings
LDetails.Add(FName); // Add string 1
LDetails.Add(LName); // 2
LDetails.Add(Dpt); // 3
LDetails.Add(Grade); // 4
LDetails.Add(NumberOfHours); // 5
//OutPut the data into the file
string LDetailsCSV = string.Join(",", LDetails.ToArray());
Console.WriteLine(LDetailsCSV);
objWriter.Write(LDetailsCSV);
objWriter.Close();
}
}
}
有人建议。
答案 0 :(得分:9)
您必须以追加模式打开文件,如下所示:
System.IO.StreamWriter objWriter;
objWriter = new File.AppendText(file_name);
答案 1 :(得分:9)
如果文件存在,StreamWriter constructor将覆盖您正在使用的文件。有一个overloaded constructor你可以传递一个布尔值作为第二个参数来告诉它追加:
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(file_name, true);
此外,您使用的Write方法不会附加换行符。如果您使用WriteLine方法,则会。
Console.WriteLine(LDetailsCSV);
objWriter.WriteLine(LDetailsCSV);
objWriter.Close();
答案 2 :(得分:2)
在你的情况下,我认为你最好做一些事情:
File.AppendAllText("EmployeeDetails.txt", string.Join(",",new [] {FName,LName,Dpt,Grade,NumberOfHours}));