-1

I wrote this code but faced an exception that said: Parameter Not Valid.

    string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = connstr;

    conn.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;

    cmd.CommandText = "SELECT * FROM tbl";

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;

    DataTable dt = new DataTable();
    da.Fill(dt);

    byte[] barrImg = (byte[])dt.Rows[1]["image"];

    MemoryStream mstream = new MemoryStream();

    mstream.Write(barrImg, 0, barrImg.Length);
    mstream.Seek(0, SeekOrigin.Begin);

    img.Image = Image.FromStream(mstream);
    mstream.Close();

The exception is:

Parameter is not valid.

in the Image.FromStream line of code.

I checked the value that in datatable was assigned to the image field. It was System.Byte[]. I traced the code. Every thing seems to be correct. But it does not work.

I searched around this problem. Another site preferred to set mstream.Position = 0. But that does not work.

I stored my image by this code.If it maybe that I saved this wrong!

    string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = connstr;

    conn.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;

    string sql = "INSERT INTO tbl (name, family, image) VALUES ('name', 'family', '{0}')";
    sql = string.Format(sql, Image.FromFile("test.jpg"));

    cmd.CommandText = sql;
    cmd.ExecuteNonQuery();
    conn.Close();

new code to save the image:

public byte[] ReadFile(string sPath)
{
    byte[] data = null;


    FileInfo fInfo = new FileInfo(sPath);
    long numBytes = fInfo.Length;

    FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

    BinaryReader br = new BinaryReader(fStream);

    data = br.ReadBytes((int)numBytes);

    return data;
}

and :

private void cmdSave_Click(object sender, EventArgs e)
{
    string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

      byte[] imageData = ReadFile("test.jpg");

      SqlConnection CN = new SqlConnection(connstr);

      string qry = "insert into tbl (name, family, image) VALUES ('name', 'family', '{0}')";
      qry = string.Format(qry, imageData);

      SqlCommand SqlCom = new SqlCommand(qry, CN);

      CN.Open();
      SqlCom.ExecuteNonQuery();
      CN.Close();
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Amin Jalali
  • 320
  • 1
  • 5
  • 15
  • I changed this question slightly so that it reflects the actual error currently faced. The previously named one was not germaine. – NotMe Feb 10 '12 at 22:51
  • While we are at it, please post your exact error message. – NotMe Feb 10 '12 at 23:10
  • An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Additional information: Parameter is not valid. – Amin Jalali Feb 10 '12 at 23:15

3 Answers3

2

Um, that's not going to work.

Your code that "stores" the image, well, doesn't really do what you think it does.

It is putting the value "test.jpg" into the image field. That isn't the binary image data; only the filename.

So, when you go to pull it back out the Image.FromStream(mstream) call is going to blow chunks because the value "test.jpg" is not an image.. ergo: the parameter is not valid

Here is an example of what you need to be doing to actually put the image into the database:

http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server

NotMe
  • 87,343
  • 27
  • 171
  • 245
  • @Amin: You did what? You *should* have modified your image saving code. If so, update your question with the new code. – NotMe Feb 10 '12 at 23:03
  • I did this like below: code[sql = string.Format(sql, Image.FromFile("test.jpg"));] see to the main code. – Amin Jalali Feb 10 '12 at 23:05
  • 1
    @Amin: Doing a String.Format while building your inline sql **will not** work. Please read the linked article. You have to pass the actual image data as a binary object to the database server. The best way to do this is through a parameterized query (which you should be doing anyway). – NotMe Feb 10 '12 at 23:09
  • I had read this article today morning and I had problem with this. – Amin Jalali Feb 10 '12 at 23:18
  • @Amin: Did you copy the code from the article *exactly*? If so, restructure your save code above rerun it and post that error message. – NotMe Feb 10 '12 at 23:25
  • I can not answer my post so I have to edit the main post.see my code in main post please. – Amin Jalali Feb 10 '12 at 23:35
1

You close the stream then try to pull an image from the stream, hence the error "cannot access a closed stream."

Try swapping the order of your last two lines:

img.Image = Image.FromStream(mstream);
mstream.Close();
JYelton
  • 35,664
  • 27
  • 132
  • 191
  • @JYelton: I assume you haven't read until "I cleared the line mstream.Close(); but faced to another Exceptioon that said: Parameter is not valid. in last line of code" below the code ;) – Tim Schmelter Feb 10 '12 at 22:22
  • Thanks for mention.Take it easy! – Amin Jalali Feb 10 '12 at 22:24
  • @Tim Point taken, though that at least clears up one of the problems. – JYelton Feb 10 '12 at 22:28
  • For the exception "Parameter is not valid..." that usually has to deal with the data not being of a correct image type or format. Look at these related questions: [629955](http://stackoverflow.com/questions/629955/parameter-not-valid-exception-loading-system-drawing-image), [3036560](http://stackoverflow.com/questions/3036560/parameter-is-not-valid-when-getting-image-from-stream), [1614773](http://stackoverflow.com/questions/1614773/image-fromstreampostedfile-inputstream-fails-parameter-is-not-valid-async) – JYelton Feb 10 '12 at 22:31
  • I edited the post.now you can my saving way of image if it is wrong. – Amin Jalali Feb 10 '12 at 22:44
0
using (MemoryStream mstream = new MemoryStream((byte[])dt.Rows[1]["image"]))
{
    img.Image = Image.FromStream(mstream);
}

Would simplify things. I suspect your problem would be you need to call mStream.Flush() after write and before the seek.

To put an image in to a database, one way is.

string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

using(SqlConnection conn = new SqlConnection(connstr))
{
  using (SqlCommand comm = new SqlCommand(conn))
  {
    comm.CommandText = "INSERT INTO tbl (name, family, image) VALUES (@name,@family,@Content)";
    comm.Parameters.Add(new SqlParameter("name",DbType.String,"Fred"));
    comm.Parameters.Add(new SqlParameter("family",DbType.String,"Flintstone"));
    using(FileStream fs = new FileStream("FredWilmaBamBamAndDino.jpg",FileMode.Open,FileAccess.Read))
    {
      comm.Parameters.Add(new SqlParameter("content",DbType.Image,fs));
    }
    cmd.ExecuteNonQuery();
  }
}

Notice it puts the content of teh file in the database. Since in the case of a jpg that content is most definitely not a string, use a parameterised query. Which youi should be doing anyway, develop a good habit. You also need to suss out using, your code was leaking resources all over the place.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
  • 1
    Forget it. Ask another question. How do I store the image and not the name of the file it was in, in my database.... – Tony Hopkinson Feb 10 '12 at 22:51
  • I tested this but faced the same Exception. what is happend? – Amin Jalali Feb 10 '12 at 22:57
  • No point in testing retrieving an image from a database when you've put a string in it is there! Would you like the code to do that, or do you want to keep on using your version which never will? – Tony Hopkinson Feb 10 '12 at 23:33
  • Interesting solution that. Never going to work mind. That will put the classname of the variable in the database as in System.Drawing.Image. – Tony Hopkinson Feb 11 '12 at 00:00