Displaying an icon in a picturebox

Sri Harsha Chilakapati picture Sri Harsha Chilakapati · Apr 3, 2013 · Viewed 15.3k times · Source

I am trying to display icon file in a picture box. I'm using this code to set the image.

pictureBox1.Image = new Icon(openFileDialog.FileName, new Size(48, 48)).ToBitmap();

But I'm getting this exception.

System.ArgumentOutOfRangeException: Requested range extends past the end of the array.
   at System.Runtime.InteropServices.Marshal.CopyToNative(Object source, Int32 startIndex, IntPtr destination, Int32 length)
   at System.Runtime.InteropServices.Marshal.Copy(Byte[] source, Int32 startIndex, IntPtr destination, Int32 length)
   at System.Drawing.Icon.ToBitmap()

How to overcome this problem?

Thanks.

Answer

Sri Harsha Chilakapati picture Sri Harsha Chilakapati · Apr 3, 2013

Solved the problem.

pictureBox1.Image = Bitmap.FromHicon(new Icon(openFileDialog.FileName, new Size(48, 48)).Handle);