Filehelpers将datetime导入sql

时间:2014-08-10 13:50:38

标签: c# sql asp.net csv filehelpers

我正在使用Filehelpers并且我正在尝试导入包含两个日期时间字段(ddMMyyy hh:mm)的CSV文件,我无法将其上传到我的表格。

我试过了:

 public class TBAtable
    {
        public string BookingNum;
        public string IdVessel;
        public float Length;
        public float Beam;
        public float SumDraught;
        public int Capacity;
        public float GrossTon;
        public static string Pentry;
        public static string Pdepart;
        public string Berth;

    }

 protected void UploadA(object sender, EventArgs e)
    {

        string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload2.PostedFile.FileName);
        FileUpload2.SaveAs(excelPath);

        SqlServerStorage storage = new SqlServerStorage(typeof(TBFtable), ConfigurationManager.ConnectionStrings["bd"].ConnectionString);


        storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlCustA);

        TBAtable[] res = CommonEngine.ReadFile(typeof(TBAtable), excelPath) as TBAtable[];
        storage.InsertRecords(res);

        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Données enregistrées avec succès !')", true);
    }
    protected string GetInsertSqlCustA(object record)
    {
        TBAtable obj = (TBAtable)record;
        CultureInfo enUS = new CultureInfo("en-US");
        DateTime PortEntry = DateTime.ParseExact(TBAtable.Pentry, "dd/MM/yyyy HH:mm:ss.fff", enUS, DateTimeStyles.None);
        DateTime PortDeparture = DateTime.ParseExact(TBAtable.Pdepart, "dd/MM/yyyy HH:mm:ss.fff", enUS, DateTimeStyles.None);


        return String.Format("INSERT INTO TA (BookingNum, IdVessel, Length, Beam, SumDraught,Capacity, GrossTon, PortEntry,PortDeparture,Berth ) " + " VALUES ( '{0}' , '{1}' , '{2}' , '{3}', '{4}' , '{5}' , '{6}', '{7}' , '{8}' , '{9}'  ); ", obj.BookingNum, obj.IdVessel, obj.Length, obj.Beam, obj.SumDraught , obj.Capacity ,obj.GrossTon , PortEntry , PortDeparture , obj.Berth  );

    } 

基本上我将DateEntry和DateDeparture字段更改为字符串,然后我尝试将这些字符串转换为正确的日期时间格式,以便我可以在sqlserver中的表中插入这些值。

我收到此错误:System.ArgumentNullException ..  我该怎么办?

1 个答案:

答案 0 :(得分:0)

转换为DateTime无法处理TBAtable.Pentry为空的情况。

请改用TryParseExact。 MSDN文档为here

DateTime portEntry = DateTime.MinValue;
bool isValidDateTime = DateTime.TryParseExact(null, "dd/MM/yyyy HH:mm:ss.fff", enUS, DateTimeStyles.None, out portEntry);

if (!isValidDateTime)
{
    // throw? log? ignore?
}