Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.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# 用于下载图像的c foreach循环只工作一次_C#_Url_Webclient - Fatal编程技术网

C# 用于下载图像的c foreach循环只工作一次

C# 用于下载图像的c foreach循环只工作一次,c#,url,webclient,C#,Url,Webclient,我正在创建一个pc窗口应用程序,从网站url下载图像。允许用户选择要下载到的文件夹 但我的问题是foreach循环只做一次这个过程 public bool Url_checker(string link) { try { //Creating the HttpWebRequest HttpWebRequest request = WebRequest.Create(link.Trim()) as HttpWebRequest; //

我正在创建一个pc窗口应用程序,从网站url下载图像。允许用户选择要下载到的文件夹

但我的问题是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设计在这里

最后的结果是,

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

谢谢

这是新代码,已清理 私有无效提交\u单击对象发送者,事件参数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();
    }
所以在调试之后,我发现错误在

下面是我在等待的时候发生的事情。它只下载了一张图片。 尝试将foreach的内容置于Try/catch下。。。
从字符串endofur=..

开始,我认为这实际上是您的Url\u checker方法在捕获异常时返回false。 当我逐字测试代码时,我得到了相同的结果,它只下载第一个图像。 如果我使用下面的Url\u检查器,它会在每次工作时处理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;
        }
    }
这是因为您必须在响应完成时处理它,否则底层基础结构不知道您对结果做了什么,并且无法为下一个响应重用连接

编辑:比我聪明的人能澄清这是否是因为没有完整地阅读响应,所以您必须明确地处理它

编辑2:没关系。从HttpWebResponse上的文档中:

决不应直接创建HttpWebResponse类的实例。相反,应使用调用HttpWebRequest.GetResponse返回的实例。必须调用Stream.Close或HttpWebResponse.Close方法来关闭响应并释放连接以供重用。不必同时调用Stream.Close和HttpWebResponse.Close,但这样做不会导致错误

编辑3:Oops,原来OP也是对的。我习惯性地用他最初测试时使用的WebClient来包装他的WebClient,而且它也可以工作。作为记录,你也可以对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;
我是说


因此,您可以检查SubString方法是否有错误。问题是此程序只循环一次!但是,没有下面的代码。FOR循环工作正常。下面的代码就是问题所在

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;
                        }

你试过添加断点并一步一步地调试吗?你能添加更多细节吗?为什么OP会成功地将foreach置于try/catch下?问题是@Equalsk是WebClient/下载文件partI know,它从昨天起就包含在我编辑过的答案中并给出了解释。谢谢。我用了很长时间终于找到了解决方案。如果你ant要将输出读取为字符串,可以执行string yourstring=System.Text.Encoding.UTF8.GetStringdata;
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}
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;
                        }