在C#中有人可以教我如何將這個程序的輸出寫入一個csv和每次都有唯一ID的文本文件嗎?喜歡而不是寫入控制檯,我希望一切都能同時進入csv文件和文本文件。而且對於txt文件還包括一個唯一的ID作爲記錄保存。寫入CSV和文本文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Product
{
public string description;
public double price;
public int count;
public Product(string description, double price, int count)
{
this.description = description;
this.price = price * count;
this.count = count;
}
public string GetDetailLine()
{
return String.Format(count + " {0}: {1:c}", description, price);
}
}
class Program
{
static void Main(string[] args)
{
int AdultTicket;
int KidTicket;
int PopcornOrder;
int DrinkOrder;
double tax = .05;
List<Product> products = new List<Product>();
Console.Write("How many adults? ");
int.TryParse(Console.ReadLine(), out AdultTicket);
Product adultTicket = new Product("Adult Ticket(s)", 7.75, AdultTicket);
products.Add(adultTicket);
Console.Write("How many kids? ");
int.TryParse(Console.ReadLine(), out KidTicket);
Product kidTicket = new Product("Kid Ticket(s)", 5.75, KidTicket);
products.Add(kidTicket);
Console.Write("Do you want popcorn? ");
string input = Console.ReadLine();
if (input.ToUpper() == "YES")
{
Console.Write ("How many? ");
int.TryParse(Console.ReadLine(), out PopcornOrder);
Product popcorn = new Product("Small popcorn", 3.50, PopcornOrder);
products.Add(popcorn);
}
Console.Write("Do you want a drink? ");
string input2 = Console.ReadLine();
if (input2.ToUpper() == "YES")
{
Console.Write("How many? ");
int.TryParse(Console.ReadLine(), out DrinkOrder);
Product drink = new Product("Large Soda", 5.50, DrinkOrder);
products.Add(drink);
Console.Clear();
}
int count = 0;
for (int i = 0; i < products.Count; i++)
{
count += products[i].count;
}
double total = 0;
for (int i = 0; i < products.Count; i++)
{
Console.WriteLine("\t\t" + products[i].GetDetailLine());
total += products[i].price;
}
Console.WriteLine("\nYour sub total is: {0:c}", total);
Console.WriteLine("Tax: {0:c}", total * tax);
Console.WriteLine("Your total is: {0:c}", total * tax + total);
Console.ReadLine();
}
}
}
您是指CSV文件(逗號分隔值)還是CVS,源代碼管理系統? –
CSV,逗號分隔值。抱歉,是我的錯。 –
不用擔心。它在答案中有所不同。看看String類的Join成員。它允許您使用選定的分隔符來加入字符串集合。 http://msdn.microsoft.com/en-us/library/tk0xe5h0.aspx –