Creating a CSV File in C#
I am trying to created a csv file where each entry is inputed by the user. Once one set of of values have been entered it should move on to the next. However I cannot seem to do the bit. Each time i run the program, it replaces the previous values.
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();
}
}
}
开发者_运维百科
Some advise please.
The StreamWriter constructor will overwrite the file you are using if it exists. There is an overloaded constructor to which you can pass a boolean as a second argument to tell it to append:
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(file_name, true);
In addition, the Write method you are using will not append a line break. If you use the WriteLine method, it will.
Console.WriteLine(LDetailsCSV);
objWriter.WriteLine(LDetailsCSV);
objWriter.Close();
You have to open the file in append mode, like this:
System.IO.StreamWriter objWriter;
objWriter = new File.AppendText(file_name);
In your case I think you are better off doing something like:
File.AppendAllText("EmployeeDetails.txt", string.Join(",",new [] {FName,LName,Dpt,Grade,NumberOfHours}));
精彩评论