Search code examples
sql-serverwcfdatacontractbinaryfilesnettcpbinding

How to pass an Excel file from a WinForms client to a WCF service and into an SQL Server table?


How to pass an Excel file from a WinForms client to a WCF service and into an SQL Server table?

Can anyone provide any guidance, code, or advice?

  1. WCF service contract and implementation that will take an Excel file as a parameter
  2. Contract implementation should insert that Excel file into a varbinary(MAX) column in SQL Server.

Solution

  • I'm sure the experts out there can improve upon this, but here are the basics ...

    On the Server

    1a. Add a new OperationContract to your Interface (eg. IService.cs)

    [OperationContract]
    string UploadBinaryFile(byte[] aByteArray);
    

    1b. Insert into SQL Server table, in your contract Implementation (eg. Service.cs)

    public string UploadBinaryFile(byte[] aByteArray)
    {
        try
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = MyConnectionString; // from saved connection string
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTestTable(BinaryFile) VALUES (@binaryfile)", conn))
            {
                cmd.Parameters.Add("@binaryfile", SqlDbType.VarBinary, -1).Value = aByteArray;
                cmd.ExecuteNonQuery();
            }
    
            return "1"; // to me, this indicates success
        }
        catch (Exception ex)
        {
            return "0: " + ex.Message; // return an error indicator + ex.message
        }
    }
    

    On the Client

    2a. Use the OpenFileDialog component to browse for files on your filesystem using the standard dialogue box that's used by most Windows applications.

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        txtUploadFilePath.Text = openFileDialog1.FileName;
    }
    

    2b. Load the file's contents into a byte array

    var byte[] BinaryFile = System.IO.File.ReadAllBytes(txtUploadFilePath.Text);
    

    2c. Call your WCF contract, passing in the byte array

    string UploadResponse = client.UploadBinaryFile(BinaryFile);
    

    It's working... YAY :-)