未处理的异常:System.Net.WebException

时间:2019-07-13 05:04:36

标签: c# exception

我有一个C#程序,该程序需要一个URL并将图像从网站上下载到用户计算机。该程序似乎可以正常工作直到第21张图像,然后遇到错误(https://i.imgur.com/v8fZ77D.png)。我不确定为什么会这样。

static void Main(string[] args)
{
    int num = 0;
    GrantAccess("C:\\My kitty collection");
    for (int i = 0; i > -1 ; i++)
    {
        FindSrc();
        num++;
        Console.WriteLine("src number" + num.ToString());
        Console.WriteLine(pah);
        try
        {
            SaveImage(pah + "\\kitty" + num.ToString() + ".jpg", ImageFormat.Jpeg, src);
        }
        catch (ExternalException)
        {
            //Something is wrong with Format -- Maybe required Format is not
            // applicable here
            Console.WriteLine("Error:Wrong Format");
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("Error: Stream is bad");
            //Something wrong with Stream
        }
    }
}

//this method finds the img source
public static void FindSrc()
{
    string url = "https://www.google.com/search?q=kitty&source=lnms&tbm=isch&sa=X&ved=0ahUKEwix57KhhbHjAhWSB80KHa21BL8Q_AUIECgB&biw=1920&bih=920";
    WebClient client = new WebClient();
    string html = code(url);
    int beg = html.Substring(start).IndexOf("img height")+start;
    int mid = html.Substring(beg).IndexOf("src");
    int end = html.Substring(beg + mid + 5).IndexOf("\"");
    src = html.Substring(beg + mid + 5, end);
    start = beg + mid + 5 + end;
    Console.WriteLine(src);
}

//this method downloads the image given the source, path, and format.
public static void SaveImage(string filename, ImageFormat format, string imageUrl)
{
    WebClient client = new WebClient();
    Stream stream = client.OpenRead(imageUrl);
    Bitmap bitmap; bitmap = new Bitmap(stream);
    if (bitmap != null)
        bitmap.Save(filename, format);
    stream.Flush();
    stream.Close();
    client.Dispose();
}

//this method creates a folder and give writing permissions 
public static void GrantAccess(string file)
{
    bool exists = System.IO.Directory.Exists(file);
    if (!exists)
    {
        DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
        pah = di.FullName;
        Console.WriteLine("The Folder is created Sucessfully");
    }
    else
    {
        Console.WriteLine("The Folder already exists");
    }

    DirectoryInfo dInfo = new DirectoryInfo(file);
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
    dInfo.SetAccessControl(dSecurity);
}

}

}

我希望程序可以继续下载图像,直到关闭为止,但是它给了我错误“未处理的异常:System.Net.WebException”

1 个答案:

答案 0 :(得分:0)

现在,您可以使用自定义图像搜索API搜索图像。 转到-https://cse.google.com/cse/all

参考: