【问题标题】:Add foreach loop around Webclient resulting in error在 Webclient 周围添加 foreach 循环导致错误
【发布时间】:2014-10-28 16:40:09
【问题描述】:

在围绕 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”或其依赖项之一。系统找不到指定的文件。

【问题讨论】:

    标签: c# xml foreach webclient


    【解决方案1】:

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

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

    await downloader.DownloadStringAsync(uri);
    

    这里有一些了解它的方法:

    【讨论】:

    • 添加此代码时出现此错误:Cannot await 'void' @abatishchev
    猜你喜欢
    • 2014-12-24
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多