使用IndexOf方法提取子字符串时出错?

时间:2013-09-15 16:54:54

标签: c# string

这是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace DownloadImages
{
    public partial class Form1 : Form
    {
        string f;

        public Form1()
        {
            InitializeComponent();

            string localFilename = @"d:\localpath\";

                using (WebClient client = new WebClient())
                {
                    client.DownloadFile("http://www.sat24.com/foreloop.aspx?type=1&continent=europa#",localFilename + "test.html");
                }

                f = File.ReadAllText(localFilename + "test.html");
                test();
        }

        private void test()
        {
            List<string> imagesUrls = new List<string>();
            int startIndex = 0;
            int endIndex = 0;
            int position = 0;

            string startTag = "http://www.niederschlagsradar.de/images.aspx";
            string endTag = "cultuur=en-GB&continent=europa";    
            startIndex = f.IndexOf(startTag);

            while (startIndex > 0)
            {

                endIndex = f.IndexOf(endTag,startIndex);
                if (endIndex == -1)
                {
                    break;
                }
                string t = f.Substring(startIndex, endIndex - startIndex + endTag.Length);
                imagesUrls.Add(t);    
                position = endIndex + endTag.Length;    
                startIndex = f.IndexOf(startTag,position);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

List中最后包含63个索引。 例如,第一个索引0包含:

http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&datum=201309151800&cultuur=en-GB&continent=europa
例如,

索引5包含:

http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&datum=201309160600&cultuur=en-GB&continent=europa

最后一个索引是问题,它包含我想要的其他索引中的字符串,但它还包含来自最后一个索引的其余文件内容:

这是最后一个索引的一部分:

http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&cultuur=thumbnail&continent=europa" border="0"/></a></li><li style="margin-top: -12px;text-align: center;"><a href="/?ir=true&co=true&li=false" target="_top" class="white"><div 

但最后一个索引应该只是:

http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.precip&cultuur=thumbnail&continent=europa

我该如何解决?