简体   繁体   English

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

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

I can get a URI from Bing Maps but when I try to save the resulting file (eg, a .jpg) it is empty (eg, 1 x 1 size). 我可以从Bing Maps获取URI,但是当我尝试保存生成的文件(例如.jpg)时,它是空的(例如1 x 1大小)。 I've got it working fine in a WPF app with event handling but how do I do it with a console app? 我已经在带有事件处理的WPF应用程序中很好地工作了,但是如何通过控制台应用程序来实现呢?

Here's the code that works with WPF but the same code fails in a console app - I think it must be because the file is saved in an event handler and (far as I know) you can't do that in a console app. 这是与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;
  }
}

For a console application, it may be simpler to download and save the file synchronously, eg with WebClient.DownloadFile() . 对于控制台应用程序,同步下载和保存文件可能更简单,例如使用WebClient.DownloadFile()

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

I'm not sure what is going wrong with your event-based code. 我不确定您的基于事件的代码出了什么问题。

My first guess is that the application drops out of Main() and exits before the background download completes. 我的第一个猜测是该应用程序退出Main()并在后台下载完成之前退出。 In that case, you may need to block the main thread until your vImage_DownloadCompleted event is completed. 在这种情况下,您可能需要阻塞主线程,直到完成vImage_DownloadCompleted事件为止。

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

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