简体   繁体   English

如何读取多个文件的C#?

[英]how to read Multiple file c#?

Currently i am reading a specific .csv and with each of them one by one need help i am a rookie coder. 目前,我正在阅读特定的.csv,并且每个人都需要帮助,我是菜鸟编码器。
for this Example i need to Read all the .csv files which is present in the folder 对于此示例,我需要读取文件夹中存在的所有.csv文件

my existing code 我现有的代码

class Program
{
    static void Main(string[] args)
    {
        string csv_file_path = @"C:\Sample files\L.csv";
        DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
    }
}

I'd recommend looking into using a DirectoryInfo to find all of the files in the given directory. 我建议您使用DirectoryInfo查找给定目录中的所有文件。 A DirectoryInfo is essentially an object that contains information about all files and directories within a directory. DirectoryInfo本质上是一个对象,其中包含有关目录中所有文件和目录的信息。 You can loop through all the files in that directory using the DirectoryInfo 's GetFiles function and look for CSV files. 您可以使用DirectoryInfoGetFiles函数遍历该目录中的所有文件,并查找CSV文件。 From there it's just a matter of doing whatever it is you intend to do with each file. 从那里开始,您只需要对每个文件进行任何处理即可。

Directory Info Documentation Link 目录信息文档链接

Also, I noticed you're using an absolute path here: 另外,我注意到您在这里使用绝对路径:

string csv_file_path = @"C:\Sample files\L.csv";

This is typically considered to be bad practice, and for good reason. 通常认为这是不好的做法,并且有充分的理由。 What happens if this program is run on any machine other than the one you're programming it on? 如果该程序在您正在编程的计算机之外的任何其他计算机上运行,​​会发生什么情况? It's probably better to use relative paths rather than absolute paths for this kind of thing so that your code can work more universally. 对于这种事情,最好使用相对路径而不是绝对路径,这样您的代码可以更通用地工作。 Relative paths are, as they sound, paths that are relative to the current file location. 相对路径是听起来相对于当前文件位置的路径。

Here is an article about relative and absolute paths for you in case you wish to learn more about that. 如果您想了解更多有关相对路径和绝对路径的信息,请参见以下文章。 A bit of Googling can also help if you're still confused on that. 如果您仍然对此感到困惑,那么使用Google谷歌搜索也会有所帮助。

I think this works for you 我觉得这对你有用

List<string> directory = Directory.EnumerateFiles(folderPath, "*.csv");

                if (directory.Count() != 0)
                {
                    foreach (string filePath in directory)
                    {
                        DataTable csvDataTable = GetDataTablefromCSV(filePath);
                    }
                }

The csv function CSV功能

public static DataTable GetDataTablefromCSV(string filePath)
        {
            try
            {
                StreamReader _streamReader = new StreamReader(filePath);
                string[] headers = _streamReader.ReadLine().Split(',');
                DataTable dataTable = new DataTable();
                foreach (string header in headers)
                {
                    dataTable.Columns.Add(header);
                }
                while (!_streamReader.EndOfStream)
                {
                    string[] rows = Regex.Split(_streamReader.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
                    DataRow dataRow = dataTable.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dataRow[i] = rows[i];
                    }
                    dataTable.Rows.Add(dataRow);
                }
                return dataTable;
            }
            catch(Exception ex)
            {
                return null;
            }            
        }

I modified code to work with multiple csv files. 我修改了代码以使用多个csv文件。 See changes below 查看下面的更改

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string csv_file_path = @"C:\Sample files";
            DataTable csvData = new DataTable();

            string[] files = Directory.GetFiles(csv_file_path, "*.csv");
            Boolean firstFile = true;
            foreach (string file in files)
            {
                GetDataTabletFromCSVFile(file, csvData, firstFile);
                firstFile = false;
            }
        }

        private static void GetDataTabletFromCSVFile(string csv_file_path, DataTable csvData, Boolean firstFile)
        {  
            try
            {
                int lineCount = 0;
                using (StreamReader  csvReader = new StreamReader(csv_file_path))
                {
                    string line = "";
                    while ((line = csvReader.ReadLine()) != null)
                    {
                        string[] colFields = line.Split(new char[] { ',' }).ToArray();
                        if (++lineCount == 1)
                        {
                            if (firstFile)
                                //read column names
                                foreach (string column in colFields)
                                    csvData.Columns.Add(column, typeof(string));
                        }
                        else
                        {
                            //Making empty value as null
                            for (int i = 0; i < colFields.Length; i++)
                                if (colFields[i] == "")
                                    colFields[i] = null;

                            csvData.Rows.Add(colFields);
                        }
                    }
                }
            }
            catch (Exception) { }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM