In Focus

Forums - C# Corner

Forum guidelines
Sayan Chatterjee

Sayan Chatterjee

  • 1.5k
  • 12
  • 960

MS SQL string connection problem

Aug 4 2017 1:35 PM
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 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;

SqlParameter paramSize = new SqlParameter();
paramName.ParameterName = "@Size";
paramName.Value = filesize;

SqlParameter paramImageData = new SqlParameter();
paramName.ParameterName = "@ImageData";
paramName.Value = bytes;


Answers (11)


Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now