2012-11-27 20 views
2

我正在編寫一個非常簡單的方法將csv轉換爲數據表,以便它可以插入到SQL數據庫中。它的工作原理應該如何,除非我嘗試用DBNull.Value替換空字符串,然後拋出一個ArrayTypeMismatchException。流入的數據是一個簡單的逗號分隔文件。獲取ArrayTypeMismatchException與對象數組

問題代碼:

public static DataTable StreamToTable(Stream stream, bool headersAvailable, bool convertBlankToDBNull) 
    { 

     DataTable data = new DataTable(); 
     StreamReader reader = new StreamReader(stream); 

     if (!reader.EndOfStream) 
     { 
      if (headersAvailable) 
      { 
       try 
       { 
        //get headers from first line 
        string[] headers = reader.ReadLine().Split(','); 

        //construct headers 
        for (int i = 0; i < headers.Length; i++) 
        { 
         data.Columns.Add(headers[i]); 
        } 
       } 
       catch (IOException ioEx) 
       { 
        return null; 
       } 
      } 

      while (!reader.EndOfStream) 
      { 
       object[] row = reader.ReadLine().Split(','); 

       if (convertBlankToDBNull) 
       { 
        for (int i = 0; i < row.Length; i++) 
        { 
         if (row[i].ToString().Equals("")) 
         { 
          row[i] = DBNull.Value; //this is where I get the exception 
         } 
        } 
       } 
       data.Rows.Add(row); 
      } 

      return data; 
     } 
     else return null; 
    } 

我想不出什麼我做錯了......我應該能夠任何分配給數組,因爲它是一個對象數組,所以怎麼可能有類型不匹配?

回答

2

您已經發現了unsafe array covariance的恐怖。

rowstring[]已被不安全地轉換爲object[]。即使該演員成功,該陣列仍然是string[](因爲這就是Split()返回),並且不能使用作爲object[]使用
特別是,它仍然不能裝東西不是string秒。

相反,你可以創建一個新的object[]並與string小號來填充它:

object[] row = Array.ConvertAll(
    reader.ReadLine().Split(','), 
    s => (object)s 
); 
+0

非常感謝!你已經向我展示了一些將來會非常有幫助的事情,因爲我相信我會再次遇到這種情況! – jbenscoter

+0

我準備在類似問題上撞到牆上。這個答案非常有幫助!謝謝你的幫助!! – christopheralan88