2017-10-09 89 views
0

文件即時試圖讀取正在尋找這樣的:導入與文件「」作爲分隔符

123,123,123h123m,123123123

而且我下面的代碼嘗試讀取:

public DataTable DataTableFromTextFile(string location, char delimiter = ',') 
{ 
    DataTable result; 

    string[] LineArray = File.ReadAllLines(path); 

    result = FormDataTable(LineArray, delimiter); 

    return result; 
} 

private static DataTable FormDataTable(string[] LineArray, char delimiter) 
{ 
    DataTable dt = new DataTable(); 

    AddColumnToTable(LineArray, delimiter, ref dt); 

    AddRowToTable(LineArray, delimiter, ref dt); 

    return dt; 
} 

private static void AddRowToTable(string[] valueCollection, char delimiter, ref DataTable dt) 
{ 

    for (int i = 1; i < valueCollection.Length; i++) 
    { 
     string[] values = valueCollection[i].Split(delimiter); 
     DataRow dr = dt.NewRow(); 
     for (int j = 0; j < values.Length; j++) 
     { 
      dr[j] = values[j]; 
     } 
     dt.Rows.Add(dr); 
    } 
} 

private static void AddColumnToTable(string[] columnCollection, char delimiter, ref DataTable dt) 
{ 
    string[] columns = columnCollection[0].Split(delimiter); 
    foreach (string columnName in columns) 
    { 
     DataColumn dc = new DataColumn(columnName, typeof(string)); 
    } 
} 

但它似乎還沒有工作。我試圖改變一些東西,但它然後去DataGridView(這被稱爲infoTabelle)添加空格。 任何人都可以幫助我解決我的問題?

****編輯 知道了一切現在。我改變了將分隔文本放入DataGridView的方法。現在的工作就像一個魅力**

+3

你什麼錯誤? 「似乎不起作用」會使你在這裏無處可尋。順便也歡迎!我建議參加[參觀]並閱讀[問]。 – Fildor

+1

順便提一下:'ref DataTable dt' - 爲什麼你認爲'ref'在這裏需要? – Fildor

+0

將一些單元測試添加到您的代碼中,以確保每個單獨的方法按預期工作。分別測試分割和驗證DataTable。你甚至從這裏得到一個有效的數據表? –

回答

1

您正在尋找這樣的事情:

// Simple: quotation "..." e.g. "123,456",789 is not implemented 
private static DataTable FromCsvSimple(string path, char delimiter = ',') { 
    // Try avoiding ReadAllLines; use ReadLines 
    // Where - let's skip empty lines (if any) 
    var lines = File 
    .ReadLines(path) 
    .Where(line => !string.IsNullOrWhiteSpace(line)) 
    .Select(line => line.Split(delimiter)); 

    DataTable result = new DataTable(); 

    foreach (string[] items in lines) { 
    // Do we have any columns to add? 
    for (int c = 0; c < items.Length; ++c) 
     while (c >= result.Columns.Count) 
     result.Columns.Add(); 

    result.Rows.Add(items); 
    } 

    return result; 
} 

... 

DataTable myTable = FromCsvSimple(@"c:\MyCsv.csv", ';'); 
相關問題