Replies: 2 comments 2 replies
-
Here is a way you can get type conversion errors and bad data errors. Keep in mind that some bad data could completely ruin reading the rest of the file. void Main()
{
var s = new StringBuilder();
s.Append("Id,Name\r\n");
s.Append("1,one\r\n");
s.Append("2a,two\r\n");
s.Append("3,three\r\n");
s.Append("b4,four\r\n");
s.Append("5,five\"foo\r\n");
var records = new List<Foo>();
var errors = new List<string>();
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
};
using (var reader = new StringReader(s.ToString()))
using (var csv = new CsvReader(reader, config))
{
csv.Context.RegisterClassMap<FooMap>();
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
try
{
records.Add(csv.GetRecord<Foo>());
}
catch (BadDataException ex)
{
errors.Add($"BadData: Line: {csv.Parser.RawRow}, Record: '{csv.Parser.RawRecord}'");
}
catch (TypeConverterException ex)
{
errors.Add($"TypeConversion: Line: {csv.Parser.RawRow} Field: '{ex.Text}', Record: '{csv.Parser.RawRecord}'");
}
}
}
errors.Dump();
records.Dump();
}
private class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
private class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.Id);
Map(m => m.Name);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Thank you for the code example! I will need to play around with that. Regarding the raw record, how would i get the particular row value that caused the error for that column? Suppose: So for the raw record of row one, I want the DateTime value, and not everything else |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I would like to do the following:
For example, if i had:
DateTime, Amount
03/14/2021, sdfd,
s%$3, 7
The program could see the Amount value in row 1 is bad, and grab the column name "Amount" and put into a list.
Likewise, in row 2 the DateTime row entry is detected and bad, and the column name "DateTime" is put into the list.
Then if that list contains values, an error is thrown to the user.
I don't have code for this, just wondering if it is possible and what tools can i use?
Currently I use Validate for each model variable, but that stops the program on the first error discovered.
Beta Was this translation helpful? Give feedback.
All reactions