*csv string conversion

I read a *.csv files into a string variable. I then split it into separate lines. My next task seems to convert the string values into values corresponding the elements of an XML file the values are supposed to be written to. This is an example of a line in this csv file:

14-Sep-2006, 6.44, 6.44, 6.3, 6.32, 26300, 6.32

In the XML file which is supposed to be a recipient for this string the column types are defined as: DateTime, float, float, float, float, long, float.

I ran into a problem converting the first string into DateTime. Of course, I can do it an awkward way split the date 14-Sept-2006 by delimited "-", etc, etc.

Is there a standard built in class or function that can do it

Another question pertains the float type. The IntelliSense does not offer an option Convert.ToFloat (). I could Convert.ToDecimal. Would it create a conflict for me in terms of writing into the XML file later

And yet another question: Convert.ToInt32() will probably be a substritute for long

Thanks.




Answer this question

*csv string conversion

  • CharlieRussell

    Thank you very much.

  • Kartit

    Thank you both. Very informative.

  • Kirti Mistry

    Thanks again, but I do have a question. There was an omission on my part when I typed the string up from memory. The year is actually coded not as 14-Sep-2006 but 14-Sep-06. When I converted the string to date (I used an awkward long method of string reshuffling) I ended up first with the value: 14-Sep-0006. I had to introduce a correction.

    Some files will contain years below 2000 like 14-Sep-1988.

    I am wondering how this little nasty thing is being handled in C#

    Thanks.



  • JohanNL

    About first part, to convert string to datetime, the best method is to use ParseExact mothod of DateTime class:
    datePart = DateTime.ParseExact(line.Split(',')[0], "dd-MMM-yyyy", new CultureInfo("en-EN"));

    When converting string to floating point type of value, you should take special care about decimal separator. You can parse string using method of splitting string on two parts and parse them, and then create final value from two values:
    //numberText = 6.44
    wholePart = Convert.ToDecimal(numberText.Split('.'));
    decimalPart = Convert.ToDecimal(numberText.Split('.') / 100m;
    final = wholePart + decimalPart;

    or you can change decimal point '.' with current culture decimal point and make a conversion as a whole string:
    final = Convert.ToDecimal(numberText.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator));

    You can chose what ever you like, I personally prefer second one, because is much clear and easy to use.



  • Terry A. King

    With a quick search on MSDN you can find all date format: http://msdn2.microsoft.com/en-us/library/8kb3ddd4.aspx

  • bishoycom

    Well, the format for that string is dd-MM-yy instead of dd-MM-yyyy

  • *csv string conversion