1

我正在使用以下function内容将csv文件导入datatable对象,但是在使用从数据中删除引号时csvData,我遇到了一个oject reference我想了解更多的问题:Regex.Replace

private static DataTable Gettabledata(string cpath)
    {
        DataTable csvData = new DataTable();

        try
        {
            using (TextFieldParser csvReader = new TextFieldParser(cpath))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;
                string[] colFields = csvReader.ReadFields();
                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }
                while (!csvReader.EndOfData)
                {

                    string[] fieldData = csvReader.ReadFields();
                    string pattern="\""; % remove quotation mark "
                    string replacement=""; % replace by empty.(eg "a", a) 
                    Regex rgx = new Regex(pattern);
                    for (int i = 0; i < fieldData.Length; i++)
                        fieldData[i] = Regex.Replace(fieldData[i],pattern, replacement); %object reference issue

                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
        }
        catch (Exception ex)
        {
        }
        return csvData;
    }
4

1 回答 1

0

fieldData[i] = Regex.Replace(fieldData[i],pattern, replacement);是在街区{...}之外。它应该在里面。

for (int i = 0; i < fieldData.Length; i++)
{
    if (fieldData[i] == "")
    {
         fieldData[i] = null;
    }
    else 
    {
         fieldData[i] = Regex.Replace(fieldData[i],pattern, replacement); 
    }
}
于 2016-04-12T12:16:04.643 回答