简体   繁体   中英

Display a file in WPF from a SQL Server database

I have a questions, I don´t know if is possible. First I have saved a file in a SQL Server database from a byte[] (C#) to varbinary with this code:

OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = " Seleccione la foto del Usuario";
fileDialog.ShowDialog();

if (fileDialog.FileName != null)
{
   ruta = fileDialog.FileName;
   lblnomArchivo.Content = new BitmapImage(new Uri(ruta));
   //MessageBox.Show(path);
}

public byte[] ConvertToByteArray(string path)
{
    byte[] ImageByte = null;

    try
    {
        FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
        //BinaryReader br = new BinaryReader(fs);
        //ImageByte = br.ReadBytes((int)fs.Length);

        Byte[] data = new byte[fs.Length];
        fs.Read(data, 0, Convert.ToInt32(fs.Length));
        ImageByte = data;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    return ImageByte;
}

I just want to retrieve this file in some WPF element, in a cell of a datagrid for instance can I get the name of the file and then open it....

And the file should be any file format not just image format

If you don't know what the type of the file will be when writing the application the fallback you can use is to pass the file to the operating system and have the OS select an appropriate app to open the file.

So first get it from the database and save it (including the correct extension) then, in the app, pass the file to the OS:

System.Diagnostics.Process.Start(filePathNameAndExtension);

Before doing this you could check the extension of the file name:

var extension = Path.GetExtension(filePathNameAndExtension).ToLower();

select(extension)
{
    case ".jpg":
    case ".png":
    case ".jpeg":
        type = Type.Image;
        break;
    case ".txt":
        type = Type.Text;
        break;
    default:
        type = Type.Unknown;
        break;
}

select(type)
{
    case Type.Unknown:
        System.Diagnostics.Process.Start(filePathNameAndExtension);
        break;
    case Type.Image:
        myImage = new Bitmap(filePathNameAndExtension);
        break;
    .....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM