将联系人保存并加载为CSV记录到文件

时间:2015-07-29 03:01:09

标签: c#

我正在尝试使用列表来存储和显示数据,从而在控制台应用程序中构建联系人管理器程序。我需要查看显示可用联系人摘要的报告,然后有一个菜单允许用户与该程序进行交互。我已经创建了一种将联系人作为CSV记录写入文件的方法,但我需要创建一种方法从文件中的CSV记录加载。但是我不确定如何从文件中的CSV记录中加载记录。

任何指导都将不胜感激。

public static void LoadFromFile()
    {

       CODE HERE

    }
     //Save contacts as CSV records to a file
     public static void saveToFile()
    {
        string filePath = "Your path of the location" + "filename.csv";
        if (!File.Exists(filePath))
        {
            File.Create(filePath).Close();
        }
        string delimiter = ",";
        string[][] output = new string[][]{
        new string[]{"Value1","Value2","Value3","Value4"} /*add the values that you want inside a csv file. Mostly this function can be used in a foreach loop.*/
        };
        int length = output.GetLength(0);
        StringBuilder sb = new StringBuilder();
        for (int index = 0; index < length; index++)
            sb.AppendLine(string.Join(delimiter, output[index]));
        File.AppendAllText(filePath, sb.ToString());
    }

2 个答案:

答案 0 :(得分:1)

CSV文件本质上是文本文件,其中行内的信息以逗号分隔。您可以使用StreamReader阅读它们。

有关更多高级操作,请参阅此处:http://www.codeproject.com/Articles/415732/Reading-and-Writing-CSV-Files-in-Csharp

答案 1 :(得分:1)

您可以使用LINQ将CSV文件解析为具有命名属性的对象,如this articlethe answers to this question所示。