我有一个C#程序,获取一个网址,并下载图片从网站上的用户,computer.The程序似乎很好,直到大约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”。
发布于 2019-07-13 05:30:33
现在您可以使用自定义图像搜索API搜索图像。去- https://cse.google.com/cse/all
参考文献:
https://stackoverflow.com/questions/57016312
复制相似问题