简体   繁体   中英

Convert string array value to int when empty string value is possible

I am having trouble converting a value in a string array to int since the value could possibly be null.

StreamReader reader = File.OpenText(filePath);
string currentLine = reader.ReadLine();
string[] splitLine = currentLine.Split(new char[] { '|' });
object.intValue = Convert.ToInt32(splitLine[10]);

This works great except for when splitLine[10] is null.
An error is thrown: `System.FormatException: Input string was not in a correct format.

Can someone provide me with some advice as to what the best approach in handling this would be?

Don't use convert, it is better to use int.TryParse()

eg

int val = 0;
if (int.TryParse(splitLine[10], out val))
   obj.intValue = val;

You can use a TryParse method:

int value;
if(Int32.TryParse(splitLine[10], out value))
{
    object.intValue = value;
} 
else 
{
    // Do something with incorrect parse value
}
if (splitLine[10] != null)
    object.intValue = Convert.ToInt32(splitLine[10]);
else
    //do something else, if you want

You might also want to check that splitLine.Length > 10 before getting splitLine[10] .

If you're reading something like a CSV file, and there's a chance it could be somewhat complicated, such as reading multiple values, it probably will make sense for you to use a connection string or other library-sorta-thing to read your file. Get example connection strings from http://www.connectionstrings.com/textfile , using Delimited(|) to specify your delimiter, and then use them like using (var conn = new OleDbConnection(connectionString)) . See the section in http://www.codeproject.com/Articles/27802/Using-OleDb-to-Import-Text-Files-tab-CSV-custom about using the Jet engine.

if you're looking for the least code to write, try

object.intValue = Convert.ToInt32(splitLine[10] ?? "0");

If you want to preserve the meaning of the null in splitLine[10] , then you will need to change the type of intValue to be of type Nullable<Int32> , and then you can assign null to it. That's going to represent a lot more work, but that is the best way to use null values with value types like integers, regardless of how you get them.

我会去

object.intValue = int.Parse(splitLine[10] ?? "<int value you want>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM