Home > Enterprise >  Compare column of a table with images in a folder on the server - VB.NET / SQL Server
Compare column of a table with images in a folder on the server - VB.NET / SQL Server

Time:01-06

In my Product Registration form, I have a Photo button to show the product photo in a pictubox1.

When the user clicks the photo button, the code will make a comparison between the prdCod column of the Products table and the filename of the image in the Photo folder on the server, and when found, it will show the corresponding image in picturebox1.

Photo button, execute the commands below:

Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
        
        Dim IdProduto As String = prdCod   ** column in Products table that will be used for the search image in the Photos folder

        If File.Exists("\\server\cmg\projects\Photos" & IdProduto) Then   ** Search the image from the Photos folder on the server
           PictureBox1.Image = Image.FromFile("\\server\cmg\projects\Photos" & IdProduto)
        End If
    End Sub

On the line

If File.Exists("\\server\cmg\projects\Photos" & IdProduto)

I have 2 problems:

  • The image's filetype is being read in the comparison with the prdCod and I need to compare only the filename of the image for it to work;
  • When the image's filename has leading zeros, the comparison doesn't work either.

Note #1: these images will not be saved in the Products table, they will already be in the Photos folder on the server and are only for being shown in picturebox1.

Note #2: the filenames of the images in the Photos folder will always be numbers and will never be repeated, ex.:\

    1.png, 2.png, 3.bmp, 4.jpg, 5.bmp, 6.jpeg... 

How do I compare only the image filename from the Photos folder, without the filetype, and also ignoring the leading zeros?

CodePudding user response:

There is no easy solution to that. You basically have to iterate through all files in the folder, use e.g. Path.GetFileNameWithoutExtension and remove leading zeros from that, before you do your comparison.

A better way ofc. would be to redesign the workflow and store the corresponding real filename (or even the fully qualified filename) along with the product code.

CodePudding user response:

You can use the GetFiles method and use a wildcard for the extension.

Private Sub AddImageIfExists(idProduto As String)
    Dim folder As New DirectoryInfo("\\server\cmg\projects\Photos")
    If folder.Exists Then
        Dim file = folder.GetFiles($"{idProduto}.*").FirstOrDefault
        If file IsNot Nothing Then
            PictureBox1.Image = Image.FromFile(file.FullName)
        End If
    End If
End Sub

That will add the photo if present.

To call the method:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim IdProduto As String = prdCod
    AddImageIfExists(IdProduto)
End Sub
  • Related