Skip to content

Commit a108702

Browse files
Fix IndexOutOfRangeException in LoadFromText with trailing columns (#2388)
Co-authored-by: Lieven De Foor <lieven.de.foor@tvh.com>
1 parent c6ef977 commit a108702

2 files changed

Lines changed: 26 additions & 8 deletions

File tree

src/EPPlus/LoadFunctions/LoadFromTextBase.cs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,16 +62,18 @@ protected bool IsEOL(string text, int ix, string eol)
6262

6363
protected object ConvertData(T Format, eDataTypes[] dataType, string v, int col, bool isText)
6464
{
65-
if (isText && (dataType == null || dataType.Length < col))
66-
{
67-
return string.IsNullOrEmpty(v) ? null : v;
68-
}
69-
else
65+
bool isOutOfBounds = dataType == null || col >= dataType.Length;
66+
67+
if (isOutOfBounds)
7068
{
71-
if(dataType == null || dataType.Length < col)
72-
return ConvertData(Format, eDataTypes.Unknown, v, col, isText);
73-
return ConvertData(Format, dataType[col], v, col, isText);
69+
if (isText)
70+
{
71+
return string.IsNullOrEmpty(v) ? null : v;
72+
}
73+
return ConvertData(Format, eDataTypes.Unknown, v, col, isText);
7474
}
75+
76+
return ConvertData(Format, dataType[col], v, col, isText);
7577
}
7678

7779
protected object ConvertData(T Format, eDataTypes? dataType, string v, int col, bool isText)

src/EPPlusTest/LoadFunctions/LoadFromTextTests.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,5 +467,21 @@ public void ReadFixedTextFile3()
467467
}
468468
}
469469

470+
[TestMethod]
471+
public void ShouldLoadCsvFormatWithTrailingColumns()
472+
{
473+
// This test verifies that importing a text/CSV file with more columns than specified in DataTypes does not crash.
474+
// Previously, an off-by-one bounds check (dataType.Length < col) allowed the loop to attempt accessing dataType[col]
475+
// when 'col' was equal to 'dataType.Length', resulting in a System.IndexOutOfRangeException.
476+
// With the fix (col >= dataType.Length), trailing columns beyond the DataTypes array are gracefully imported as Unknown (General).
477+
AddLine("a;2;extra");
478+
_format.Delimiter = ';';
479+
_format.DataTypes = new eDataTypes[] { eDataTypes.String, eDataTypes.Number };
480+
_worksheet.Cells["A1"].LoadFromText(_lines.ToString(), _format);
481+
Assert.AreEqual("a", _worksheet.Cells["A1"].Value);
482+
Assert.AreEqual(2d, _worksheet.Cells["B1"].Value);
483+
Assert.AreEqual("extra", _worksheet.Cells["C1"].Value);
484+
}
485+
470486
}
471487
}

0 commit comments

Comments
 (0)