用于下载图像的c#foreach循环只运行一次

时间:2015-06-21 21:05:48

标签: c# url webclient

我正在创建一个从网站网址下载图片的PC窗口应用程序。允许用户选择要下载的文件夹。

但我遇到的问题是foreach循环只执行一次这个过程......

public bool Url_checker(string link)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(link.Trim()) 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 TRUE if the Status code == 200
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch (WebException)
    {
        return false;
    }
}

private void submit_Click(object sender, EventArgs e)
{
    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
    folderBrowserDialog1.ShowDialog();
    string saveToThisFolder = folderBrowserDialog1.SelectedPath ;
    int i = 0;
    var di = new DirectoryInfo(saveToThisFolder);
    di.Attributes &= ~FileAttributes.ReadOnly;

    int counter = 0;
       foreach (string x in urllist.Lines)
       {
           string EndOfURL = x.Substring(x.Length - 4);
           if (Url_checker(x) && (EndOfURL == ".jpg" || EndOfURL == ".gif" || EndOfURL == ".jpeg" || EndOfURL == ".png"))
           {
              byte[] data;
             //using (WebClient client = new WebClient())
              //{
              WebClient client = new WebClient();
                  data = client.DownloadData(x);
             // }

              File.WriteAllBytes(saveToThisFolder + @"\" + (i++ + EndOfURL), data);
              counter++;
              workingURL.Text += x; //+ System.Environment.NewLine
           }
          else
          {

              errorURL.Text += (x + System.Environment.NewLine);
          }
       }


    folderBrowserDialog1.Dispose();
}

GUI设计就在这里。

enter image description here

最后的结果就是这个,

enter image description here

它只打印和下载一次。它似乎,它只读取文本框的第一行。或者foreach循环是错误的。

谢谢

这是新的CODE,CLeaned  private void submit_Click(object sender,EventArgs e)         {

        FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
        folderBrowserDialog1.ShowDialog();
        string saveToThisFolder = folderBrowserDialog1.SelectedPath;
        int i = 0;
        var di = new DirectoryInfo(saveToThisFolder);
        di.Attributes &= ~FileAttributes.ReadOnly;

        int counter = 0;
        foreach (string x in urllist.Lines)
        {
            try
            {
                string EndOfURL = x.Substring(x.Length - 4);
                if (Url_checker(x) && (EndOfURL == ".jpg" || EndOfURL == ".gif" || EndOfURL == ".jpeg" || EndOfURL == ".png"))
                {

                    byte[] data;
                    using (WebClient client = new WebClient())
                    {                            
                      data = client.DownloadData(x);
                      File.WriteAllBytes(saveToThisFolder + @"\" + ("MotivatinalQuoteImage" + (i++) + EndOfURL), data);
                      counter++;
                      workingURL.Text += x + System.Environment.NewLine;
                    }
                }
                else
                {
                    errorURL.Text += (x + System.Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                errorURL.Text += ex;
            }

        }
        folderBrowserDialog1.Dispose();
    }

所以在调试之后,我发现错误是在

之间的某个地方
                       byte[] data;
                       using (WebClient client = new WebClient())
                       {
                           data = client.DownloadData(x);
                           File.WriteAllBytes(saveToThisFolder + @"\" + ("MotivatinalQuoteImage" + (i++) + EndOfURL), data);
                           counter++;
                           workingURL.Text += x + System.Environment.NewLine;
                       } 

这是我等待时发生的事情。之后它只下载了1张图片。 http://i.imgur.com/eBtOW1w.png

4 个答案:

答案 0 :(得分:3)

我认为实际上你的Url_checker方法在捕获异常时返回false 当我逐字测试你的代码时,我得到相同的结果,它只下载第一张图片 如果我使用以下Url_checker,每次HttpWebResponse处理 public bool Url_checker(string link) { try { HttpWebRequest request = WebRequest.Create(link.Trim()) as HttpWebRequest; request.Method = "HEAD"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { return (response.StatusCode == HttpStatusCode.OK); } } catch (WebException) { return false; } }

WebClient

这是因为您必须在完成后处理响应,否则底层基础结构不知道您对结果所做的操作,并且无法重用该连接以进行下一次响应。

编辑:可以比我更聪明的人澄清这是否是因为没有完整地阅读回复,所以你必须明确处理它?<​​/ p>

编辑2:没关系。来自HttpWebResponse的文档:

https://msdn.microsoft.com/en-us/library/system.net.httpwebresponse%28v=vs.110%29.aspx

  

您永远不应该直接创建HttpWebResponse类的实例。而是使用通过调用HttpWebRequest.GetResponse返回的实例。 您必须调用Stream.Close或HttpWebResponse.Close方法来关闭响应并释放连接以便重用。没有必要同时调用Stream.Close和HttpWebResponse.Close,但这样做不会导致错误。

编辑3:糟糕,结果OP也是对的。我在测试时习惯性地将他的using包裹在using(他最初做过)中,它也有效。为了记录,你也可以FolderBrowserDialog对你的byte[] data; using (WebClient client = new WebClient()) { data = client.DownloadData(x); } File.WriteAllBytes(saveToThisFolder + @"\" + (i++ + EndOfURL), data); counter++; workingURL.Text += x + System.Environment.NewLine; 进行处理,而不是自己处理它,尽管它们都有效。

RAMDirectory

答案 1 :(得分:0)

尝试将foreach的内容置于try/catch下... 从string EndOfUrl =....

开始

答案 2 :(得分:0)

我的意思是

foreach (string x in urllist.Lines)
   {
try
{
       string EndOfURL = x.Substring(x.Length - 4);
       if (Url_checker(x) && (EndOfURL == ".jpg" || EndOfURL == ".gif" || EndOfURL == ".jpeg" || EndOfURL == ".png"))
       {
          byte[] data;
         //using (WebClient client = new WebClient())
          //{
          WebClient client = new WebClient();
              data = client.DownloadData(x);
         // }

          File.WriteAllBytes(saveToThisFolder + @"\" + (i++ + EndOfURL), data);
          counter++;
          workingURL.Text += x; //+ System.Environment.NewLine
       }
      else
      {

          errorURL.Text += (x + System.Environment.NewLine);
      }
   }
}
catch(Exception ex)
{//todo : add some logging here}

所以你可以检查SubString方法是否有错误

答案 3 :(得分:0)

问题是这个程序只通过ONCE LOOPS!但是,没有下面的代码。 FOR LOOP完美运作。下面的代码就是问题。

byte[] data;
                        using (WebClient client = new WebClient())
                        {                            
                          data = client.DownloadData(x);
                          File.WriteAllBytes(saveToThisFolder + @"\" + ("MotivatinalQuoteImage" + (i++) + EndOfURL), data);
                          counter++;
                          workingURL.Text += x + System.Environment.NewLine;
                        }