Question

I want to save image as stream in SQL database, I have doing that in silverlight as:

 OpenFileDialog fd = new OpenFileDialog();
 if (fd.ShowDialog() == true)
 {
     Stream stream = fd.File.OpenRead();
     byte[] binaryImage = new byte[stream.Length];
     stream.Read(binaryImage, 0, (int)stream.Length);

     BitmapImage bitmapImage = new BitmapImage();
     bitmapImage.SetSource(stream);
     _business.PersonalPhoto = binaryImage;
 }

With WPF this code does not work, fd.File does not exist. How can I correct this code to work on WPF

Thanks in advance.

Was it helpful?

Solution 3

Finally I have solved this, here is the code for store the image in database as binary :

To store the image:

       Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
        if (fd.ShowDialog() == true)
        {
            ILogo.Source = new BitmapImage(new Uri(fd.FileName));

            Stream stream = File.OpenRead(fd.FileName);
            binaryImage = new byte[stream.Length];
            stream.Read(binaryImage, 0, (int)stream.Length);
        }

        _merchantInfo.Logo = binaryImage;
        _context.SaveChanges();

Thanks for everyone helped me :)

OTHER TIPS

You might change your code as follow

Microsoft.Win32.OpenFileDialog  fd = new Microsoft.Win32.OpenFileDialog ();
    if (fd.ShowDialog() == true)
    {
        Stream stream = File.OpenRead(fd.FileName);
        byte[] binaryImage = new byte[stream.Length];
        stream.Read(binaryImage, 0, (int)stream.Length);

        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.SetSource(stream);
        _business.PersonalPhoto = binaryImage;
    }

Use the FileName property of the OpenFileDialog instead:

Stream stream = File.OpenRead(fd.FileName);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top