"Dialogs must be user-initiated." with SaveFileDialog in Silverlight 3

pencilslate picture pencilslate · Aug 31, 2009 · Viewed 32.3k times · Source

I am working on a Silverlight 3 app with C#. I would like to allow the user to download an image from the Silverlight app. I am using SaveFileDialog to perform the file download task. The flow goes this way:

  1. User clicks on Download button in the SL app.
  2. Web service call invoked to get the image from server
  3. OnCompleted async event handler of the web method call get invoked and receives the binary image from the server
  4. Within the OnCompleted event handler, SaveFileDialog prompted to user for saving the image to computer.
  5. Stream the image to the file on user's harddrive.

I am using the following code in a function which is called from the OnCompleted event handler to accomplish SaveFileDialog prompt and then streaming to file.

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "JPG Files|*.jpg" + "|All Files|*.*";
            bool? dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                using (Stream fs = (Stream)dialog.OpenFile())
                {
                    fs.Write(e.Result, 0, e.Result.Length);
                    fs.Close();
                }
            }

The SaveFileDialog would throw the error "Dialogs must be user-initiated." when invoking ShowDialog method in the above code. What could i be missing here? How to overcome this?

Answer

KeithMahoney picture KeithMahoney · Aug 31, 2009

What this error message means is that you can only show a SaveFileDialog in response to a user initiated event, such as a button click. In the example you describe, you are not showing SaveFileDialog in response to a click, but rather in response to a completed http request (which is not considered a user initiated event). So, what you need to do to get this to work is, in the Completed event of the http request, show some UI to the user saying "download completed, click here to save the file to your computer", and when the user clicks on this message, display the SaveFileDialog.