Search code examples
c#argumentexception

Unhandled System.ArgumentException.. Additional Information: Parameter is not valid


I have this code in c# that pulls images from database and shows them in PictureBox. Whenever I run code first, I get this error saying "An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Additional information: Parameter is not valid." But if I terminate and rerun the program, it works just fine giving intended results. Here is part of the code that is giving me trouble:

 private void buttonGetImage_Click(object sender, EventArgs e)
    {
        string baseUrl = "http://someurl";
        HttpWebRequest request = null;
        foreach (var fileName in fileNames)
        {
            string url = string.Format(baseUrl, fileName);
            MessageBoxButtons buttons = MessageBoxButtons.OKCancel;
            DialogResult result;
            result = MessageBox.Show(url, fileName, buttons);

            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                this.Close();
            }

            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = container;

            response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();

            byte[] buffer = new byte[10000000];
            int read, total = 0;

            while ((read = stream.Read(buffer, total, 1000)) != 0)
            {
                total += read;
            }
            MemoryStream ms = new MemoryStream(buffer, 0, total);
            ms.Seek(0, SeekOrigin.Current);
            Bitmap bmp = (Bitmap)Bitmap.FromStream(ms);
            pictureBoxTabTwo.Image = bmp;
            this.pictureBoxTabTwo.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBoxTabTwo.Image.Save("FormTwo.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }

Can someone help me to figure out what can be done? Error is showing me line --> Bitmap bmp = (Bitmap)Bitmap.FromStream(ms);


Solution

  • Instead of using Bitmap class I used Image class in my program. What I was doing here was taking a stream and putting it into a byte array. And again converting content of that array back to stream. Instead, I used

    Image img = Image.FromStream(stream)
    

    In this case You don't even have to use MemoryStream. It is working perfectly find for me now.