在Webclient周围添加foreach循环导致错误

时间:2014-10-28 16:40:10

标签: c# xml foreach webclient

在Webclient任务周围添加foreach循环时,它会发出以下错误

foreach (string rssFeed in lstRSSFeeds)
{
    // our web downloader
    WebClient downloader = new WebClient();

    // our web address to download, notice the UriKind.Absolute
    Uri uri = new Uri(rssFeed, UriKind.Absolute);

    // we need to wait for the file to download completely, so lets hook the DownloadComplete Event
    downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(FileDownloadComplete);

    // start the download
    downloader.DownloadStringAsync(uri);
}

public void FileDownloadComplete(object sender, DownloadStringCompletedEventArgs e)
{
    // e.Result will contain the files byte for byte

    // your settings
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.DtdProcessing = DtdProcessing.Ignore;

    // create a memory stream for us to use from the bytes of the downloaded file
    MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(e.Result ?? ""));

    // create your reader from the stream of bytes
    XmlReader reader = XmlReader.Create(ms, settings);
    SyndicationFeed feed = SyndicationFeed.Load(reader);

    // do whatever you want with the reader
    // ........
    reader.Close();
}

导致错误:

  

mscorlib.ni.dll中出现'System.IO.FileNotFoundException'类型的第一次机会异常

     

其他信息:无法加载文件或程序集'System.Windows.debug.resources,Version = 2.0.6.0,Culture = en-US,PublicKeyToken = 7cec85d7bea7798e'或其中一个依赖项。系统找不到指定的文件。

1 个答案:

答案 0 :(得分:0)

您需要坚持使用当前的同步和基于事件的模型并使用DownloadString方法。

或者(鼓!)欢迎来到async await的世界,所以对于返回await的方法,请使用关键字Task<T>

await downloader.DownloadStringAsync(uri);

以下是了解它的方法: