سؤال

I have the following code which writes to a SQL Server database:

private void InsertResult(Result results, string messageId)
{
   object chkresult = (results);

   MemoryStream memStream = new MemoryStream();
   StreamWriter sw = new StreamWriter(memStream);

   sw.Write(chkresult);

   SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Reporting"].ConnectionString);

   using (conn)
   {
      using (SqlCommand cmd = new SqlCommand())
      {
         conn.Open();

         cmd.CommandText = "Results_Ins";
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.Add("@Id", SqlDbType.VarChar, 50).Value = messageId;
         cmd.Parameters.Add("@result", SqlDbType.VarBinary, Int32.MaxValue);
         cmd.Parameters["@result"].Value = memStream.GetBuffer();
         cmd.Parameters.Add("@RowCount", SqlDbType.Int).Direction = ParameterDirection.Output;

         cmd.Connection = conn;

         try
         {
             cmd.ExecuteNonQuery();
         }
         catch (Exception err)
         {
             // handle the error
             //messageInsert = false;
         }
         finally
         { 
             conn.Close(); 
         }
      }
   }

   //return rowCount;
}

When I execute this code, I get 0x being stored in the Result column. I'm not sure this is correct, and therefore I need some help.

Basically, I need to store a complete object into a single column in a SQL Server database table.

هل كانت مفيدة؟

المحلول

You either need to call Flush or cause sw to be Closed or Disposed in order to ensure that it's finished writing to the memStream.

Also, instead of GetBuffer, you should use ToArray. GetBuffer returns an internal buffer which may be larger than the amount of bytes that have actually been written.


You should also change this:

catch (Exception err)
{
   // handle the error
   //messageInsert = false;
}

to only catch specific exceptions for which you have a strategy to deal with them.


And, even now, I don't think it's going to do what you wanted (which you haven't really spelled out). All that your sw.Write call does is:

Writes the text representation of an object to the text string or stream by calling the ToString method on that object.

If you want actual serialization to occur, you're going to need to write code that causes it to happen - after picking whether you want to perform binary or xml serialization.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top