在c#中将多个csv文件上传到SQL Server

时间:2016-05-23 16:42:12

标签: c# sql-server csv ftp filehelpers

我的问题解决了。我出于隐私原因删除了我的代码

2 个答案:

答案 0 :(得分:1)

我不太确定你的意思 我希望能够从三个不同的文件夹一次一个地读取文件 但这里有一个解决方案它将遍历一个文件夹的csv文件,为您提供读取每个文件并执行您需要执行的操作的选项,然后将文件移动到新文件夹。

private void ProcessFilesCSVFiles(string copyPath, string destinationPath)
{
    // first check if path exists
    if (!Directory.Exists(copyPath))
        // doesn't exist then exit, can't copy from something that doesn't exist
        return;
    var copyPathDirectory = new DirectoryInfo(copyPath);
    // using the SearchOption.AllDirectories will search sub directories
    var copyPathCSVFiles = copyPathDirectory.GetFiles("*.csv", SearchOption.AllDirectories);
    for(var i = 0; i < copyPathCSVFiles.Length; i++)
    {
        // get the file
        var csvFile = copyPathCSVFiles[i];
        // read the csv file line by line
        using (StreamReader sr = csvFile.OpenText())
        {
            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                // use split to read the individual columns
                // will fail if the text field has a comma in it
                var split = line.Split(',');
                Console.WriteLine(line);
            }
        }
        // do other sql mojo here if needed

        // move the files over to another place
        var destinationFilePath = Path.Combine(destinationPath, csvFile.Name);
        if (File.Exists(destinationFilePath))
        {
            File.Delete(destinationFilePath);
        }
        csvFile.MoveTo(destinationFilePath);
    }
}

使用类似的东西调用:

ProcessFilesCSVFiles(@"C:\data\copypath", @"C:\data\destinationpath");

答案 1 :(得分:0)

看看this related question

您需要进行一些更改,例如将文件扩展名更改为“.csv”并更改目标文件路径。

foreach (var file in d.GetFiles("*.csv"))
{
    //Load CSV into SQL using existing code
    Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}