Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试捕获-URL链接不存在_C#_Url_Try Catch - Fatal编程技术网

C# 尝试捕获-URL链接不存在

C# 尝试捕获-URL链接不存在,c#,url,try-catch,C#,Url,Try Catch,我需要从URL读取一些数据-但取决于字符串(ICAO)-URL有时不存在(无效)。在这种情况下-我应该得到“不适用”-但这不起作用。。。只有当所有三个URL都可读时,它才起作用 [Invoke] public List<Category> getWeather(string ICAO) { try { List<Category> lstcat = new List<Catego

我需要从URL读取一些数据-但取决于字符串(ICAO)-URL有时不存在(无效)。在这种情况下-我应该得到“不适用”-但这不起作用。。。只有当所有三个URL都可读时,它才起作用

        [Invoke]
    public List<Category> getWeather(string ICAO)
    {
        try
        {
            List<Category> lstcat = new List<Category>();
            Category cat = new Category();
            string fileString;
            bool isexists = FtpDirectoryExists("ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/" + ICAO);
            if (isexists == true)
            {
                WebClient request = new WebClient();
                string url = "http://weather.noaa.gov/pub/data/observations/metar/stations/" + ICAO;
                byte[] newFileData = request.DownloadData(url);
                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
                cat.Cat = "METAR";
                lstcat.Add(cat);
                cat = new Category();
                cat.Cat = fileString;
                lstcat.Add(cat);
                url = "http://weather.noaa.gov/pub/data/forecasts/shorttaf/stations/" + ICAO;
                newFileData = request.DownloadData(url);

                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
                cat = new Category();
                cat.Cat = "Short TAF";
                lstcat.Add(cat);
                cat = new Category();
                cat.Cat = fileString;
                lstcat.Add(cat);

                url = "http://weather.noaa.gov/pub/data/forecasts/taf/stations/" + ICAO;
                newFileData = request.DownloadData(url);

                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
                cat = new Category();
                cat.Cat = "Long TAF";
                lstcat.Add(cat);
                cat = new Category();
                cat.Cat = fileString;
                lstcat.Add(cat);

            }
            else
            {
                fileString = "N/A;N/A";
            }
            return null;
        }
        catch (Exception)
        {

            throw;
        }
    }
[调用]
公共列表getWeather(字符串ICAO)
{
尝试
{
List lstcat=新列表();
类别cat=新类别();
字符串文件字符串;
bool isexists=FtpDirectoryExists(“ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/“+民航组织);
如果(isexists==true)
{
WebClient请求=新建WebClient();
字符串url=”http://weather.noaa.gov/pub/data/observations/metar/stations/“+民航组织;
字节[]newFileData=request.DownloadData(url);
fileString=System.Text.Encoding.UTF8.GetString(newFileData);
cat.cat=“METAR”;
lstcat.Add(cat);
cat=新类别();
cat.cat=fileString;
lstcat.Add(cat);
url=”http://weather.noaa.gov/pub/data/forecasts/shorttaf/stations/“+民航组织;
newFileData=request.DownloadData(url);
fileString=System.Text.Encoding.UTF8.GetString(newFileData);
cat=新类别();
cat.cat=“短TAF”;
lstcat.Add(cat);
cat=新类别();
cat.cat=fileString;
lstcat.Add(cat);
url=”http://weather.noaa.gov/pub/data/forecasts/taf/stations/“+民航组织;
newFileData=request.DownloadData(url);
fileString=System.Text.Encoding.UTF8.GetString(newFileData);
cat=新类别();
cat.cat=“Long TAF”;
lstcat.Add(cat);
cat=新类别();
cat.cat=fileString;
lstcat.Add(cat);
}
其他的
{
fileString=“不适用;不适用”;
}
返回null;
}
捕获(例外)
{
投掷;
}
}

创建一个方法来检查远程文件是否存在。 对URl发出Heder请求,如果sattus代码为200或302,则返回true 否则为假

HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(/* url */);
request.Method = "HEAD";


try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    /* A WebException will be thrown if the status of the response is not `200 OK` */
}
finally
{
    // Don't forget to close your response.
    if (response != null)
    {
        response.Close()
    }
}

好吧,我想我知道你想做什么了。我重新编写了您的代码,使其符合实际需要

现在,似乎
lstcat
中的第一个
Category
具有第一个URL的描述(如“METAR”),而
lstcat
中的第二个
Category
具有与其匹配的
文件字符串,依此类推。这是非常模糊和繁琐的。相反,要使一个
类别
对象包含您需要了解的关于URL的所有信息:

public class Category 
{
    public string description;
    public string fileString;
    //Other fields you might use somewhere else...

    public Category(string description, string fileString /*, other fields, if any...*/)
    {
        this.description = description;
        this.fileString = fileString;
        //Initialize others...
    }
}
然后,通过将所有URL下载代码放在一个单独的函数中,我消除了原始代码中的所有重复

[Invoke]
public List<Category> getWeather(string ICAO)
{
    bool isexists = FtpDirectoryExists("ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/" + ICAO);
    if (isexists)
    {
        List<Category> lstcat = new List<Category>();

        addCategoriesToList(
            lstcat,
            "http://weather.noaa.gov/pub/data/observations/metar/stations/" + ICAO,
            "METAR"
        );
        addCategoriesToList(
            lstcat,
            "http://weather.noaa.gov/pub/data/forecasts/shorttaf/stations/" + ICAO,
            "Short TAF"
        );
        addCategoriesToList(
            lstcat,
            "http://weather.noaa.gov/pub/data/forecasts/taf/stations/" + ICAO,
            "Long TAF"
        );

        return lstcat;
    }
    else
    {
        return null;
    }
}

private static void addCategoriesToList(List<Category> lstcat, string url, string description)
{
    string fileString;
    //Use "using" so that `request` always gets cleaned-up:
    using (WebClient request = new WebClient()) 
    {
        try
        {
            byte[] newFileData = request.DownloadData(url);
            fileString = System.Text.Encoding.UTF8.GetString(newFileData);
        }
        catch
        {
            fileString = "N/A";
        }
    }

    lstcat.Add(new Category(description, fileString));
}
[调用]
公共列表getWeather(字符串ICAO)
{
bool isexists=FtpDirectoryExists(“ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/“+民航组织);
如果(存在)
{
List lstcat=新列表();
添加分类列表(
lstcat,
"http://weather.noaa.gov/pub/data/observations/metar/stations/“+国际民航组织,
“梅塔”
);
添加分类列表(
lstcat,
"http://weather.noaa.gov/pub/data/forecasts/shorttaf/stations/“+国际民航组织,
“短TAF”
);
添加分类列表(
lstcat,
"http://weather.noaa.gov/pub/data/forecasts/taf/stations/“+国际民航组织,
“长塔夫”
);
返回lstcat;
}
其他的
{
返回null;
}
}
私有静态void addCategoriesToList(列表lstcat、字符串url、字符串描述)
{
字符串文件字符串;
//使用“using”以便“request”始终得到清理:
使用(WebClient请求=新建WebClient())
{
尝试
{
字节[]newFileData=request.DownloadData(url);
fileString=System.Text.Encoding.UTF8.GetString(newFileData);
}
抓住
{
fileString=“不适用”;
}
}
添加(新类别(描述,文件字符串));
}

我认为这能以一种更干净、更直接的方式实现你想要的。如果真是这样,请告诉我

如果该FTP URL有效,您将无法访问
“N/A;N/A”
字符串。此外,您在将项目添加到
列表lstcat
时遇到了很多麻烦,但是您总是返回
null
-这真的是您想要的行为吗?不。我希望每个URL(没有响应)都有一个“N/a”。像METAR N/A,但它仍然显示其他URL内容项。嘿,Bjoern-这两个答案对你有用吗?如果是,请单击其中一个复选标记,将其标记为已接受。