MrDean MrDean - 3 months ago 10
ASP.NET (C#) Question

Retrieving images using a file path stored in a sql database

Morning all.

Newbie Mr Dean requiring some simple advice.

I have a table in my SQL database that stores an AccountID and an ImageID - the ImageID being a filepath to an actual account image in *gif format.

What would I need to to do retrieve the file path and then project this fiel path as the actual image onto an image control? I am using in c#.

Potentially, when the page is accessed, depending on which account has logged on, the appropriate image specific for the account is retrieve (I would imagine I can set up an @AccountID parameter at a later date)

If anyone has example code for something they have done similarly, I would be most grateful for any pointers you may have.


Here's a sample:

var connectionString = ConfigurationManager.ConnectionStrings["SomeCN"].ConnectionString;
using (var cn = new SqlConnection(connectionString))
using (var cmd = cn.CreateCommand())
    cmd.CommandText = "select imageid from accounts where accountid = @accountid";
    cmd.Parameters.AddWithValue("@accountid", 5);
    using (var reader = cmd.ExecuteReader())
        if (reader.Read())
            var filePath = reader.GetString(0);
            // For this to work images must be stored inside the web application.
            // filePath must be a relative location inside the virtual directory
            // hosting the application. Depending on your environment some
            // transformations might be necessary on filePath before assigning it
            // to the image url.
            imageControl.ImageUrl = filePath;