bloggerads

2013年1月1日 星期二

C# : Write / Read CSV file sample code

Write an array to test.csv

static void Main(string[] args)
{
    string filePath = System.IO.Directory.GetCurrentDirectory() + @"\test.csv";

    string[] myDataArray = new string[] { "123", "abc", "ddd"};

    File.WriteAllText(filePath, string.Join(",", myDataArray));   
}


Read  test.csv

static void Main(string[] args)
{
    string filePath = System.IO.Directory.GetCurrentDirectory() + @"\test.csv";

    var item = new List<string>();

    foreach (var line in File.ReadLines(filePath))
    {
        var array = line.Split(',');
        foreach (string idx in array)
            item.Add(idx);
    }

    string[] strArray = item.ToArray();

    foreach (string ss in strArray)
    {
        Console.WriteLine("{0}", ss);
    }
    Console.ReadLine();
}




沒有留言:

張貼留言