-1

how can I load the images from the remote server in a data table C# windows form? I have stored only the image path in my Sqldatabase. when I am running the code it throws an exception of 404 error. same code is retriving the images on other forms

screen capture

 private void Datagrid() { 
                try
                {
                    id.Text = "";
                    name.Text = "";
                    cost.Text = "";

                    price.Text = "";
                    description.Text = "";
                    status.Text = "";
                    picture.Image = null;

                    status.Items.Add("active");
                    status.Items.Add("inactive");
                    id.Visible = false;
                    label7.Text = "";
                    conn.Open();
                    MySqlCommand cm = new MySqlCommand();
                   // string query = "SELECT dealSuggestion_id,name,cost,price,description,Status from dealSuggestion where Status='inactive' LIMIT 8";
                    string query = "SELECT * from dealSuggestion where Status='inactive' LIMIT 8";

                    cm.CommandText = query;
                    cm.Connection = conn;
                    MySqlDataAdapter da = new MySqlDataAdapter(cm);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
foreach (DataRow row in dt.Rows)
                {
                    string img = row["image"].ToString();

                    if (!row.IsNull("image"))
                    {
                     ServicePointManager.Expect100Continue = true;
                        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                        System.Net.WebRequest request = System.Net.WebRequest.Create(row["image"].ToString());
                        System.Net.WebResponse resp = request.GetResponse();
                        System.IO.Stream respStream = resp.GetResponseStream();
                        Bitmap bmp = new Bitmap(respStream);
                        respStream.Dispose();
                        row["image"] = bmp;

                    }
                    }
                    dataGridView1.DataSource = dt;
                    conn.Close();
                }
                catch (Exception ex)
                {

                    MessageBox.Show("Error" + ex);
                }
            }
hassan
  • 13
  • 5
  • 1
    Too broad, you haven't described what UI framework you are using, or shown any attempt at research.please read [ask] – TheGeneral Aug 20 '19 at 05:26
  • @TheGeneral it is a winform – hassan Aug 20 '19 at 05:29
  • https://stackoverflow.com/questions/17193825/loading-picturebox-image-from-resource-file-with-path-part-3 – TheGeneral Aug 20 '19 at 05:30
  • @TheGeneral plz check it out – hassan Aug 20 '19 at 05:38
  • Are you sure that your image accessible ? – nzrytmn Aug 20 '19 at 07:56
  • @nzrytmn yes check this one path https://www.resturantapp.com/images/deal2.jpg – hassan Aug 20 '19 at 08:02
  • Can you please update your question and give more details about your UI and technologies ? The questions must creating according this guide line https://stackoverflow.com/help/how-to-ask . – nzrytmn Aug 20 '19 at 08:06
  • You're using WebRequest/WebResponse the wrong way, the Bitmap's underlying Stream, too. Use the WebClient class to download the Images (dispose of it after use). Remove this: `ServicePointManager.Expect100Continue = true;`: you really don't want it set to `true`; if you set it, set it to `false` (always). Keep `System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;` if you think your app will be used in Windows 7 (that System, if not updated to the latest security roll-up, will default to `SSL3` and `TLS1.0`). – Jimi Aug 20 '19 at 08:28

3 Answers3

1
    Imports System 
 Imports System.Runtime.InteropServices
Imports System.Security.Principal  Imports System.Security.Permissions  Public Class Form1  <DllImport("advapi32.DLL", SetLastError:=True)> _  Public Shared Function LogonUser(ByVal lpszUsername As String, ByVal lpszDomain As String, _ 
        ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _ 
        ByRef phToken As IntPtr) As Integer  End Function  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
        Dim admin_token As IntPtr 
        Dim wid_current As WindowsIdentity = WindowsIdentity.GetCurrent() 
        Dim wid_admin As WindowsIdentity = Nothing 
        Dim wic As WindowsImpersonationContext = Nothing 
        Try 

            If LogonUser("Local Admin name", "Local computer name", "pwd", 9, 0, admin_token) <> 0 Then 
                wid_admin = New WindowsIdentity(admin_token) 
                wic = wid_admin.Impersonate() 

// inside this scope you can access remote PC please note that path shouldn't contain : instead of : use $ sign
              FileStream fs = new FileStream(imagepath, FileMode.Open, FileAccess.Read);

    //Initialize a byte array with size of stream
    byte[] imgByteArr = new byte[fs.Length];

    //Read data from the file stream and put into the byte array
    fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));

    //Close a file stream
    fs.Close();

            Else 
               //custom message
            End If 
        Catch se As System.Exception 
            Dim ret As Integer = Marshal.GetLastWin32Error() 
            MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString()) 
            MessageBox.Show(se.Message) 
        Finally 
            If wic IsNot Nothing Then 
                wic.Undo() 
            End If 
        End Try  
        End Sub  
        End Class

Try this Sir please vote if its working thank you

amaldec23
  • 245
  • 2
  • 11
  • path should be something like \\\192.168.1.123\D$\Test\Test.img – amaldec23 Aug 20 '19 at 08:59
  • amaldec23 the code is working fine but can you plz tell me why datagrid view is not showing images it showing only system,drawing .bitmap – hassan Aug 20 '19 at 09:48
  • In data grid View image won't show actually you can use picturebox Control for showing picture – amaldec23 Aug 20 '19 at 10:07
  • The path should be something like: "Images\a.bmp". (Note the lack of a leading slash, and the slashes being back slashes.) And then: pictureBox1.Image = Image.FromFile(@"Images\a.bmp"); try something like this in picture box to load image from a path – amaldec23 Aug 20 '19 at 10:08
  • If (bytearraywithimage.Length > 0) Then Dim Stream As New MemoryStream(b, True) Stream.Write(bytearraywithimage, 0, bytearraywithimage.Length) Dim bmp As New Bitmap(Stream) PictureBox1.Image = bmp End If this is to load image or byte array to picture box – amaldec23 Aug 20 '19 at 10:10
0
    FileStream fs = new FileStream(imagepath, FileMode.Open, FileAccess.Read);

    //Initialize a byte array with size of stream
    byte[] imgByteArr = new byte[fs.Length];

    //Read data from the file stream and put into the byte array
    fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));

    //Close a file stream
    fs.Close();

    //assign to dt particular column imageByteArr

Hope this will help you

amaldec23
  • 245
  • 2
  • 11
0

I assume that this is a foem appliaction . You can try something like this that described in this question:

 foreach (DataRow row in t.Rows)
{
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(row["uri"].ToString());
                myRequest.Method = "GET";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
                myResponse.Close();

                row["Img"] = bmp;
}
nzrytmn
  • 6,193
  • 1
  • 41
  • 38
  • can you plz tell me datagridview is is not showing the images it only showing system.drawing.bitmap – hassan Aug 20 '19 at 09:51
  • hassan take a look on it : https://stackoverflow.com/questions/16784440/how-display-images-in-datagridview-c-sharp – Kuba Do Aug 20 '19 at 10:24
  • @hassan is is working now ? In windows form datadridview except bitmap format as a source. this is why you have to convert your webresponse to System.Drawing.Bitmap. – nzrytmn Aug 20 '19 at 10:32