问题
I am using TextReader to read in each line of a tab delimited file. For each line that it reads I split on the tabs and populate a string array. I can then access specific positions in the string array to get the values.
This works great for strings like: userWorkload.SSN = arrColumns[0];
However, I get an error message at runtime when I try to convert one of the columns to an int: userWorkload.contactHours = Convert.ToInt32(arrColumns[9]);
Here is my code:
List<UserWorkload> userWorkloads = new List<UserWorkload>();
TextReader tr = File.OpenText("fall11-tab.txt");
string strLine = string.Empty;
string[] arrColumns = null;
while ((strLine = tr.ReadLine()) != null)
{
UserWorkload userWorkload = new UserWorkload();
arrColumns = strLine.Split('\t');
userWorkload.SSN = arrColumns[0];
userWorkload.contactHours = Convert.ToInt32(arrColumns[9]);
userWorkloads.Add(userWorkload);
}
and the UserWorkload class just contains simple getter / setters:
class UserWorkload
{
public string SSN { get; set; }
public int contactHours { get; set; }
}
Here is my error:
Unhandled Exception: System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Convert.ToInt32(String value)
at Snyder5Creator.InputFileReader.buildRowList() in C:\Users\baxter.NET\Documents\Visual Studio 2010\Projects\User5Creator\User5Creator\InputFileReader.cs:line 31
at Snyder5Creator.Program.Main(String[] args) in C:\Users\baxter.NET\Documents\Visual Studio 2010\Projects\User5Creator\Snyder5Creator\Program.cs:line 24
Line 31 is: userWorkload.contactHours = Convert.ToInt32(arrColumns[9]);
Any help on this would be greatly appreciated.
回答1:
You probably have invalid data in one or more of the records. If you're OK with ignoring these errors, you could use int.TryParse:
int parsedNumber;
userWorkload.contactHours = int.TryParse(arrColumns[9], out parsedNumber) ? parsedNumber : -1;
回答2:
Wrap this in a try-catch, too.
List<UserWorkload> userWorkloads = new List<UserWorkload>();
TextReader tr = File.OpenText("fall11-tab.txt");
string strLine = string.Empty;
string[] arrColumns = null;
while ((strLine = tr.ReadLine()) != null)
{
UserWorkload userWorkload = new UserWorkload();
arrColumns = strLine.Split('\t');
userWorkload.SSN = arrColumns[0];
if(!int.TryParse(arrColumns[9], out userWorkload.contactHours)
{
//Throw something like InvalidArgumentException here or set to a safe value (-1?)
}
userWorkloads.Add(userWorkload);
}
来源:https://stackoverflow.com/questions/10589940/tab-delimited-txt-file-reading-int-value-from-string-array