Object reference on array with regex.replace()

2019-07-23 06:34发布

问题:

I am using the below function to import a csv file into a datatable object csvData, however i face an oject reference issue that i'd like to understand more while using Regex.Replace to remove quote marks from the data:

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

回答1:

The fieldData[i] = Regex.Replace(fieldData[i],pattern, replacement); is outside the {...} block. It should be inside it.

for (int i = 0; i < fieldData.Length; i++)
{
    if (fieldData[i] == "")
    {
         fieldData[i] = null;
    }
    else 
    {
         fieldData[i] = Regex.Replace(fieldData[i],pattern, replacement); 
    }
}