Object reference on array with regex.replace()

筅森魡賤 提交于 2019-12-13 19:17:39

问题


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


来源:https://stackoverflow.com/questions/36570447/object-reference-on-array-with-regex-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!