Reputation: 169
I am try to create an application using asp.net (c#) In which the user will upload a single file (any data format doc, docx,pdf) using fileupload control.
And then I have to save the contents of the file in the database selected by the user. The structure of database is:
Field DataType
id int
title nvarchar(MAX)
body varbinary(MAX)
bodyoverview nvarchar(MAX)
postedon date
The contents of the file will be saved in body attribute. Also I have the following code:
protected async void Button_Upload_Click(object sender, EventArgs e)
{
StringBuilder stringBuilder = new StringBuilder();
if(FileUpload1.HasFile)
{
try
{
string FileContent = String.Empty;
using(StreamReader inputStreamReader=new StreamReader(FileUpload1.PostedFile.InputStream))
{
FileContent = await inputStreamReader.ReadToEndAsync();
foreach (char c in FileContent.ToCharArray())
{
stringBuilder.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
}
}
SqlConnection sqlConnection = new SqlConnection("Data Source=(localdb)\\ProjectsV12;Initial Catalog=Blog;Integrated Security=True");
string query = "insert into blogthumbnails values(@blogtitle,@body,@bodyoverview,@allowcomments,@commentscount,@postedon)";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlCommand.Parameters.AddWithValue("@blogtitle", TextBox_Title_Of_The_Blog.Text);
sqlCommand.Parameters.AddWithValue("@body", stringBuilder);
sqlCommand.Parameters.AddWithValue("@postedon", DateTime.Now.Date);
await sqlConnection.OpenAsync();
try
{
int i = sqlCommand.ExecuteNonQuery();
if(i>0)
{
Label_File_Upload_Status.Text = "File Uploaded";
}
else
{
Label_File_Upload_Status.Text = "Please try again";
}
}
catch(SqlException sqlException)
{
Label_File_Upload_Status.Text = sqlException.Message.ToString();
}
}
catch(Exception FileUploadException)
{
Label_File_Upload_Status.Text = "Error in uploading file. Please try again. Error: "+FileUploadException.Message;
}
}
else
{
Label_File_Upload_Status.Text = "Please select a file to upload";
}
}
But I am getting the error:
No mapping exists from object type
System.Text.StringBuilder
to a known managed provider native type.
Upvotes: 1
Views: 4518
Reputation: 3216
Since body
is of varbinary
type thus data should be in binary format. You need to convert the result from stringBuilder
into byte array first and then you can save it in you table.
byte[] byteArray = Encoding.UTF8.GetBytes(Convert.ToString(stringBuilder));
sqlCommand.Parameters.AddWithValue("@body", byteArray);
Upvotes: 3
Reputation: 519
By default StringBuilder is not a native type that can be mapped to NVARCHAR, TEXT, INT, DEC or other native sql types.
try these:
sqlCommand.Parameters.AddWithValue("@body", stringBuilder.ToString());
Upvotes: 2
Reputation: 39037
This line: sqlCommand.Parameters.AddWithValue("@body", stringBuilder);
should be
sqlCommand.Parameters.AddWithValue("@body", stringBuilder.ToString());
Upvotes: 1