2016-05-23 157 views
-1

我的问题已解决。我为了隐私原因取下了我的代码在c中将多个csv文件上传到SQL服务器#

+0

通过“发送到SQL Server”你的意思是你想要的物理文件复制到SQL服务器的磁盘,请阅读来自文件的数据并将数据插入到表中,或者...您尝试了哪些代码以及哪些具体操作不起作用?我想如果你把这个问题分解成具体的,可回答的问题,你很可能很容易找到答案(如何将数据插入sql数据库,如何移动文件等) – DVK

回答

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