如何从c#中的文件夹中读取多个.CSV文件?

时间:2017-08-18 18:45:55

标签: c# csv

我正在编写一个控制台应用程序,它使用SmartXLS库从指定的文件夹中读取多个CSV文件。我能够从单个文件中读取但无法弄清楚如何读取多个文件。请帮助我。

public void GetData()
        {

            int count = 0;

            DeskTokens = new List<Token>();

            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string path = Path.Combine(directory, @"C:\projects\Product_Usage_Year.csv");

            SmartXLS.WorkBook WB = new WorkBook();
            WB.readCSV(path);

            DataTable dt = WB.ExportDataTable();

            string CurrentType = string.Empty;
            string CurrentCategory = string.Empty;

            DataRow dr;
            for (int i = 1; i < dt.Rows.Count; i++)
            {
                dr = dt.Rows[i];
                var tkn = new Token();

                tkn.Product_name = dr[0].ToString();
                tkn.Product_Version = dr[1].ToString();
                tkn.Userid = dr[2].ToString();
                tkn.User_name = dr[3].ToString();

                DeskTokens.Add(tkn);
                count++;
                Console.WriteLine("Read : " + count);

                Console.WriteLine("    Reading : " + tkn.Product_name + "," + tkn.Product_Version + "," + tkn.Userid + "," + tkn.User_name);

            }
        }

2 个答案:

答案 0 :(得分:3)

下面,"path"是所有CSV文件所在的目录。

var files = Directory.EnumerateFiles("path", "*.csv");
foreach (string file in files)
{
    using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
    {
        // Use the file stream to read data.
    }
}

答案 1 :(得分:0)

使用Directory.GetFiles

// Gets only .csv files 
string[] csvFiles = Directory.GetFiles(directoryPath, "*.csv");

并写一个这样的循环:

foreach(file in csvFiles)
{
   getData(file);
   // ...
}

您还应该在getData方法中使用路径参数:

public void GetData(string path)
        {

            int count = 0;

            DeskTokens = new List<Token>();

            SmartXLS.WorkBook WB = new WorkBook();
            WB.readCSV(path);

            DataTable dt = WB.ExportDataTable();

            string CurrentType = string.Empty;
            string CurrentCategory = string.Empty;

            DataRow dr;
            for (int i = 1; i < dt.Rows.Count; i++)
            {
                dr = dt.Rows[i];
                var tkn = new Token();

                tkn.Product_name = dr[0].ToString();
                tkn.Product_Version = dr[1].ToString();
                tkn.Userid = dr[2].ToString();
                tkn.User_name = dr[3].ToString();

                DeskTokens.Add(tkn);
                count++;
                Console.WriteLine("Read : " + count);

                Console.WriteLine("    Reading : " + tkn.Product_name + "," + tkn.Product_Version + "," + tkn.Userid + "," + tkn.User_name);

            }
        }

我希望对你有所帮助:)。

相关问题