检查Web上的文件夹是否存在

时间:2014-02-08 23:09:06

标签: vb.net visual-studio-2012

我正在创建桌面应用程序,当我在TextBox1Button1.Click事件中编写用户名时,应检查网络上的文件夹是否存在。
到目前为止,我已经尝试过这个:

 username = Me.TextBox1.Text
 password = Me.TextBox2.Text

        Dim dir As Boolean = IO.Directory.Exists("http://www.mywebsite.com/" + username)
        If dir = true Then
            Dim response As String = web.DownloadString("http://www.mywebsite.com/" + username + "/Password.txt")
            If response.Contains(password) Then
                MsgBox("You've logged in succesfully", MsgBoxStyle.Information)
                Exit Sub
            Else
                MsgBox("Password is incorect!")
            End If
        Else
            MsgBox("Username is wrong, try again!")
        End If

第一个问题是我的布尔值给出了FALSE作为答案(目录确实存在,所有权限都被授予查看文件夹)。我尝试通过设置dir = false来解决这个问题,然后我进入第一个IF(但这不是我想要的,因为它应该是TRUE,而不是FALSE)
我们遇到了第二个问题:Dim response As String=web.DownloadString("http://www.mywebsite.com/" + username + "/Password.txt")我收到此错误消息:The remote server returned an error: (404) Not Found.
有没有经验的人可以帮助我?

1 个答案:

答案 0 :(得分:1)

IO.Directory.Exists在这种情况下不起作用。该方法仅用于在某处(本地或网络)检查磁盘上的文件夹;您无法使用它来检查HTTP上是否存在资源。 (即URI)

  • 但即使它确实以这种方式工作,在尝试下载之前调用它实际上毫无意义 - 如果出现问题,方法DownloadString会抛出异常 - 如您所见,在这种情况下它告诉你 404 Not Found 这意味着“就你所关注的而言,这个资源并不存在”。 **

  • 所以你应该try/catch操作,你需要捕获WebException类型的异常,将其Response成员强制转换为HttpWebException,并检查StatusCode属性。 一个很好的例子(尽管在C#中)是here

**我说“就你而言”,因为据你所知,资源可能很好地存在于服务器上,但它决定将它隐藏起来,因为你无法访问它等等,该网站的开发者决定在这种情况下返回404而不是401 Unauthorized。关键在于,从您的角度来看,资源不可用。

更新

这里是我链接到的答案的代码,通过this online tool翻译,因为我的VB很狡猾:)。这个代码在LinqPad中运行得很好,并产生输出“ testlozinka

Sub Main
Try
    Dim myString As String
    Using wc As New WebClient()
        myString = wc.DownloadString("http://dota2world.org/HDS/Klijenti/TestKlijent/password.txt")
        Console.WriteLine(myString)
    End Using
Catch ex As WebException
 Console.WriteLine(ex.ToString())
    If ex.Status = WebExceptionStatus.ProtocolError AndAlso ex.Response IsNot Nothing Then
        Dim resp = DirectCast(ex.Response, HttpWebResponse)
        If resp.StatusCode = HttpStatusCode.NotFound Then
            ' HTTP 404
            'the page was not found, continue with next in the for loop
            Console.WriteLine("Page not found")
        End If
    End If
    'throw any other exception - this should not occur
    Throw
End Try
End Sub

希望有所帮助。