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:
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?
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.