繁体   English   中英

C#控制台应用程序-必应地图-如何保存输出

[英]C# Console app - Bing Maps - how to save output

我可以从Bing Maps获取URI,但是当我尝试保存生成的文件(例如.jpg)时,它是空的(例如1 x 1大小)。 我已经在带有事件处理的WPF应用程序中很好地工作了,但是如何通过控制台应用程序来实现呢?

这是与WPF一起使用的代码,但是在控制台应用程序中相同的代码失败-我认为这一定是因为文件保存在事件处理程序中,而且(据我所知)您不能在控制台应用程序中执行此操作。

public void vSaveBitmapImage(string sURI, // created with Bing Maps GeocodeServices
  string sLocFname)
{
  // save file name so event handler knows it
  this.sFname = sLocFname;

  try
  {
    BitmapImage bmpImage = new BitmapImage(new Uri(sURI, UriKind.RelativeOrAbsolute));
    // setup event handler - file is saved just fine here
    bmpImage.DownloadCompleted += vImage_DownloadCompleted;
  }
  catch (SystemException sex)
  {
    string s = sex.Message;
  }
}

/// <summary>
/// handle the event that an image download has completed
/// </summary>
private void vImage_DownloadCompleted(object sender,
  EventArgs e)
{
  try
  {
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();

    encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender));

    using (var filestream = new FileStream(this.sFname, FileMode.Create))
      encoder.Save(filestream);
  }
  catch (SystemException sex)
  {
    string s = sex.Message;
  }
}

对于控制台应用程序,同步下载和保存文件可能更简单,例如使用WebClient.DownloadFile()

var client = new WebClient();
client.DownloadFile( sURI, sLocFname );

我不确定您的基于事件的代码出了什么问题。

我的第一个猜测是该应用程序退出Main()并在后台下载完成之前退出。 在这种情况下,您可能需要阻塞主线程,直到完成vImage_DownloadCompleted事件为止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM