11
Answers

MS SQL string connection problem

I'm trying to store images in my database, located in my local pc. I'm very close to it! however, on executing the below code, I'm getting an error which says ..."Object reference not set to an instance" and it points to theline-
string cs= configurationmanager.Connectionstring.....
 
When I'm debugging with a break point..I see that the value of cs=" ".........and therefore con.open() is probably not getting the connection string as value of con=null.
 
Any Idea what should be done?
 
 
 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Configuration;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;

namespace Shop
{

public partial class addimage : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}
protected void Buttonuploadimage_Click(object sender, EventArgs e)
{
HttpPostedFile postedfile=FileUpload.PostedFile;
String filename = Path.GetFileName(postedfile.FileName);
String fileExtension = Path.GetExtension(filename);
int filesize = postedfile.ContentLength;

if(fileExtension.ToLower()==".jpg" || fileExtension.ToLower() == ".gif")
{
Stream stream = postedfile.InputStream;
BinaryReader binaryreader = new BinaryReader(stream);
Byte[] bytes = binaryreader.ReadBytes((int)stream.Length);


String cs = Convert.ToString(ConfigurationManager.ConnectionStrings[@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\Sayan\Documents\Visual Studio 2015\Projects\Shop\Shop\App_Data\Saanvi.mdf; Integrated Security = True; Connect Timeout = 30; User Instance = True"]);

SqlConnection con = new SqlConnection(cs);

{
SqlCommand cmd = new SqlCommand("spUploadImage", con);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter paramName = new SqlParameter();
{
paramName.ParameterName = "@Name";
paramName.Value = filename;
};
cmd.Parameters.Add(paramName);

SqlParameter paramSize = new SqlParameter();
{
paramName.ParameterName = "@Size";
paramName.Value = filesize;
};
cmd.Parameters.Add(paramSize);

SqlParameter paramImageData = new SqlParameter();
{
paramName.ParameterName = "@ImageData";
paramName.Value = bytes;
};
cmd.Parameters.Add(paramImageData);

con.Open();
cmd.ExecuteNonQuery();
con.Close(); 
Answers (11)