Search code examples
vb.netpathfilepath

How to get a path of an image and trim it?


I'm trying to get image upload working . So far I have this :

        Dim dlg As New OpenFileDialog
        Dim strPath As String = ""
        dlg.Filter = "PNG(*.png;)|*.png;"
        dlg.ShowDialog()

        Dim fileName As String = dlg.FileName.Trim
        Dim ftpDirectory As String = ""
        If fileName <> "" Then
            If fileName.Contains("[") AndAlso fileName.Contains("].png") Then
                MessageBox.Show("The file you have selected is on the FTP", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else

                strPath = dlg.FileName.ToString

                End If

                If button = 1 Then
                txtSmallDealOneImg.Text = strPath

However the strPath returns the whole path to image file for example C:/website/Images/page1/photo1.png

How do I trim the output so that it only shows /Images/Page1/photo1.png ?

The images are in different folders so I would need to trim everything thats followed by /images


Solution

  • So you want to remove the static "C:/website" from the path?

    Then you could simply use

    If strPath.StartsWith("C:/website") Then
        txtSmallDealOneImg.Text = strPath.Substring("C:/website".Length)
    End If
    

    If you instead want to remove everything before the Image-subdirectory you can use:

    Dim imageIndex = strPath.IndexOf("/Images/", StringComparison.InvariantCultureIgnoreCase)
    If imageIndex >= 0 Then
        txtSmallDealOneImg.Text = strPath.Substring(imageIndex)
    End If