[英]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
本质上是一个对象,其中包含有关目录中所有文件和目录的信息。 您可以使用DirectoryInfo
的GetFiles
函数遍历该目录中的所有文件,并查找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.