如何检查HTTP上是否存在文件模式?

时间:2014-04-04 10:13:12

标签: c# .net vb.net

我需要检查文件是否存在。在HTTP上可以获得在其文件名中具有模式的文件。如果存在,则接下来将下载它们。

我知道直接在HTTP上查看特定文件,但我不知道如何使用文件名模式来实现这一点,如abc * .csv?

1 个答案:

答案 0 :(得分:1)

首先,您必须检查页面是否存在:

using System.Net;
...
private bool CheckIfRemoteFileExist(string url){
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TURE if the Status code == 200
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}  

然后,如果它存在,您可以下载页面:

string content=string.Empty;
if(CheckIfRemoteFileExist("myUrl"))
    using(var client = new WebClient())
        content = client.DownloadString("myUrl");
else
    MessageBox.Show("File seems dosen't exist");