Check for file/subdirectory existence with VB.NET using FtpWebRequest

1000 views Asked by At

I have a problem with my FTP upload and I hope you can help me. I'm trying create folders and then upload files to them. What my program should do is checking if a folder already exists, and if not, create a new one with the name checked before. The program runs fine, except for the error described below.

My Problem:
I want to upload a folder called ghandle -> works as intended.
After that, I want to upload a folder called handle -> doesn't work, because the .Contains method that checks the folders on the FTP server, finds ghandle and stops, because ghandle contains handle.

Are there other options like .Contains which will just check for whole words or exact matches?

Here is my source code:

Dim dirname = Path.GetFileNameWithoutExtension(openFileDialogHtml.FileName) & "_files"    
Dim ftp = "ftp://" & ftp_address.Text & "/"
Dim user = ftp_user.Text
Dim pass = ftp_password.Text

Dim request As Net.FtpWebRequest = Net.FtpWebRequest.Create(ftp)
Dim creds As Net.NetworkCredential = New Net.NetworkCredential(user, pass)
request.Credentials = creds

Dim resp As Net.FtpWebResponse = Nothing
request.Method = Net.WebRequestMethods.Ftp.ListDirectoryDetails
request.KeepAlive = True
Using resp
    resp = request.GetResponse()
    Dim sr As StreamReader = New StreamReader(resp.GetResponseStream(), System.Text.Encoding.ASCII)
    Dim s As String = sr.ReadToEnd()
    If Not s.Contains(dirname) Then
        request = Net.FtpWebRequest.Create(ftp & dirname)
        request.Credentials = creds
        request.Method = Net.WebRequestMethods.Ftp.MakeDirectory
        resp = request.GetResponse()
        MsgBox("Created folder " & dirname)
    Else
        MsgBox("Folder " & dirname & " already exists!")
    End If
End Using

Thanks in advance

1

There are 1 answers

0
Martin Prikryl On BEST ANSWER

First, use ListDirectory, not ListDirectoryDetails. The ListDirectory returns plain names only, what is enough for your purpose and easy to parse.

Then just split the output to an array of individual file names, using the String.Split method:

Dim names As String() =
    sr.ReadToEnd().Split(
        New Char() {vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)

And use the IEnumerable.Contains extension method to check for given file name:

If Not names.Contains(dirname) Then