簡體   English   中英

如何讀取多個文件的C#?

[英]how to read Multiple file c#?

目前,我正在閱讀特定的.csv,並且每個人都需要幫助,我是菜鳥編碼器。
對於此示例,我需要讀取文件夾中存在的所有.csv文件

我現有的代碼

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

我建議您使用DirectoryInfo查找給定目錄中的所有文件。 DirectoryInfo本質上是一個對象,其中包含有關目錄中所有文件和目錄的信息。 您可以使用DirectoryInfoGetFiles函數遍歷該目錄中的所有文件,並查找CSV文件。 從那里開始,您只需要對每個文件進行任何處理即可。

目錄信息文檔鏈接

另外,我注意到您在這里使用絕對路徑:

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

通常認為這是不好的做法,並且有充分的理由。 如果該程序在您正在編程的計算機之外的任何其他計算機上運行,​​會發生什么情況? 對於這種事情,最好使用相對路徑而不是絕對路徑,這樣您的代碼可以更通用地工作。 相對路徑是聽起來相對於當前文件位置的路徑。

如果您想了解更多有關相對路徑和絕對路徑的信息,請參見以下文章。 如果您仍然對此感到困惑,那么使用Google谷歌搜索也會有所幫助。

我覺得這對你有用

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

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

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;
            }            
        }

我修改了代碼以使用多個csv文件。 查看下面的更改

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