Your code looks quite ok.
string str = (string)(MyRange.Cells[rCnt, cCnt] as Excel.Range).Value2.ToString();
The exception is probably in the above line.
Dont type case directly into
string
.
Instead either use the
null
coalesce operator
(??)
, use
Convert.ToString()
or directly check for null.
The reason is if you try and cast a null into string an exceltion will be thrown.
Here is an example of what you could do -
string str = = (MyRange.Cells[rCnt, cCnt] as Excel.Range).Value2 ?? string.empty);<br />
<br />
You could also try<br />
string str = (MyRange.Cells[rCnt, cCnt] as Excel.Range).Value2 != string.empty ? MyRange.Cells[rCnt, cCnt] as Excel.Range).Value2.toString() : string.empty;<br />
<br />
Give one of these a try and check if you still get this error.