2009-07-29 6 views
1

Cette méthode ne génère pas d'exception et ne renvoie pas non plus les lignes du fichier CSV lues dans DataTable. Je ne sais pas ce que je fais de façon incorrecte.L'importation de fichier csv dans datatable renvoie aucun résultat

Toute aide est très appréciée.

public string ImportCsvFile(string filePath) 
    { 
     FileInfo file = new FileInfo(filePath); 
     //string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + file.DirectoryName + "\" Extended Properties='text;HDR=Yes;FMT=Delimited(,)';"; 
     string connString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};" + @" Extended Properties={1}", file.DirectoryName, "'Text;HDR=YES;FMT=CSVDelimited'"); 
     using (OleDbConnection con = new OleDbConnection(connString)) 
     { 
      OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM [{0}]", file.Name), con); 
      // Using a DataTable to process the data 
      try 
      { 
       con.Open(); 
       ds = new DataTable("MyTable"); 
       OleDbDataAdapter adp = new OleDbDataAdapter(cmd); 
       adp.Fill(ds); 
       foreach (DataRow row in ds.Rows) 
       { 
        System.Diagnostics.Debug.WriteLine(row.ToString()); 
       } 
      } 
      catch (Exception error) 
      { 
       String errorString; 
       errorString = "Error occurred while importing data from source file." + System.Environment.NewLine + 
       "Error Message: " + error.Message + System.Environment.NewLine + 
       "Stack Trace: " + error.StackTrace; 
       return errorString; 
      }      
     } 
     return "File imported to DataTable"; 
    } 
+0

Juste un coup ici mais je ne vois pas un con.close(). – David

+1

Avec une instruction "using" vous n'avez pas besoin d'un appel .Close(). Il fermera et disposera de la connexion. –

Répondre

1

En fin de compte, ce code est correct. C'est le fichier csv qui a été le problème ici. Il y avait un certain type de corruption de fichier ou le format de fichier était incompatible en quelque sorte.

Questions connexes