简体   繁体   中英

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). I've got it working fine in a WPF app with event handling but how do I do it with a console app?

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.

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() .

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. In that case, you may need to block the main thread until your vImage_DownloadCompleted event is completed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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