【问题标题】:What is the quickest and simplest way to check whether a file exists online?检查文件是否在线存在的最快和最简单的方法是什么?
【发布时间】:2013-01-25 14:50:39
【问题描述】:

在线检查文件是否存在最快、最简单的方法是什么?

我知道如何检查文件系统上是否存在文件或网站是否存在,但我不知道如何在线检查文件是否存在。我该怎么做?

我想验证以下链接是否在线存在:

http://ccc-itgs2012.wikispaces.com/file/view/AP+Human+Geography+Gapminder.flv

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    您在线检查的方式与检查文件系统的方式相同:尝试访问文件,并在尝试失败时处理异常(顺便说一句:如果您在文件系统上使用 File.Exists(),则可能是doing it wrong)。

    唯一的额外问题是,在线检查时,您可以发送资源的 http 请求并访问响应流,而无需实际阅读流,这意味着您不必下载整个文件只是为了知道请求将完成。

    【讨论】:

    • 听起来很棒。你能给我一个例子吗?当我尝试过时,我永远无法让它工作
    • 也感谢 Joel 指出 File.Exists 的事情,我不知道这一点。
    • 虽然该代码有效。执行需要时间(8-15 秒) 有更快的方法吗?正如乔尔所描述的那样,它好像真的很快。
    • 您只想更改方法以返回响应对象。如果您正在查看布尔值 true/false,那么您做错了。不幸的是,这是检查易失性资源的唯一好方法是使用它们并处理异常。
    【解决方案2】:

    对于 HTTP,使用 HTTP HEAD 方法。它的行为类似于 GET 方法,只是它只返回内容标头。如果文件不存在,服务器应该返回 404 状态码。否则,您可以假设该文件存在(甚至可以从内容标题中获取其大小)。

    编辑

    您可以使用此代码:

    Public Function ResourceExists(location As Uri) As Boolean
        If (Not String.Equals(location.Scheme, Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase)) And (Not String.Equals(location.Scheme, Uri.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase)) Then
            Throw New NotSupportedException("URI scheme is not supported")
        End If
    
        Dim request = Net.WebRequest.Create(location)
        request.Method = "HEAD"
    
        Try
            Using response = request.GetResponse
                Return DirectCast(response, Net.HttpWebResponse).StatusCode = Net.HttpStatusCode.OK
            End Using
        Catch ex As Net.WebException
            Select Case DirectCast(ex.Response, Net.HttpWebResponse).StatusCode
                Case Net.HttpStatusCode.NotFound
                    Return False
                Case Else
                    Throw
            End Select
        End Try
    End Function
    

    用法:

    Dim itExists As Boolean = ResourceExists(New Uri("http://ccc-itgs2012.wikispaces.com/file/view/AP+Human+Geography+Gapminder.flv"))
    

    这确实会锁定调用者的线程,因此您可能希望将其重构为异步方法。

    【讨论】:

    • 你能给我举个例子吗?这种方法听起来确实不错
    • 我在答案中添加了一个用法示例。
    • 请注意,它只捕获错误 404(未找到)。如果服务器返回不同的错误代码,此方法将重新抛出它。
    【解决方案3】:

    此代码对我有用

    Public Function CheckAddress(ByVal URL As String) As Boolean
        Try
            Dim request As WebRequest = WebRequest.Create(URL)
            Dim response As WebResponse = request.GetResponse()
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function
    

    【讨论】:

      【解决方案4】:

      我想出的最好的方法,实际上发现它可以按需要工作,因为所有的方法都只是检查是否找到了域,所以如果找到了域而文件没有,它会仍然告诉您找到该文件,我的方法是尝试使用 DownloadFileAsync 下载该文件并运行计时器 3 秒,然后在 3 秒后检查是否从该文件下载了任何字节文件,如果有,则通过该链接可以找到该文件,如果没有,则未找到,然后您可以取消下载并删除已在您的PC上创建的文件。

      这是我的代码:

      Imports System.IO
      Imports System.Net
      Public Class Form1
          Dim BytesReceived As Integer
      
          Public WithEvents Download As WebClient
      
          Private Sub DownloadBUT_Click(sender As Object, e As EventArgs) Handles Button1.Click
              Download = New WebClient
              Download.DownloadFileAsync(New Uri("http://example.com/FileName.exe"), My.Computer.FileSystem.SpecialDirectories.Desktop & "FileName.exe")
              CheckFileTimer.Start()
              DownloadBUT.Enabled = False
          End Sub
      
          Private Sub Download_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles Download.DownloadProgressChanged
              BytesReceived = e.BytesReceived
          End Sub
      
          Private Sub CheckFileTimer_Tick(sender As Object, e As EventArgs) Handles CheckFileTimer.Tick
              CheckFileTimer.Stop()
              If BytesReceived = 0 Then
                  MsgBox("File not found!")
              Else
                  MsgBox("File found!")
              End If
              DownloadBUT.Enabled = True
              Download.CancelAsync()
              Try
                  File.Delete(My.Computer.FileSystem.SpecialDirectories.Desktop & "FileName.exe")
              Catch ex As Exception : End Try
          End Sub
      End Class
      

      希望这对你有用:)

      【讨论】:

        猜你喜欢
        • 2013-01-04
        • 2023-03-16
        • 2023-01-12
        • 1970-01-01
        • 2010-09-18
        相关资源
        最近更新 更多