(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Using the SaveFileDialog in Silverlight

(10 votes)
Nikolay Raychev
>
Nikolay Raychev
Joined Mar 28, 2008
Articles:   22
Comments:   58
More Articles
45 comments   /   posted on Mar 20, 2009
Tags:   controls , savefiledialog , nikolay-raychev
Categories:   Controls

This article is compatible with the latest version of Silverlight.

Introduction

The SaveFileDialog is a new dialog control introduced in Silverlight 3 which allows the user to save a file on the client machine.

Overview

To demonstrate the common use of the SaveFileDialog I’ll give an example:

Source code

When you click on the button a dialog window appears which allows you to save a file.

In the XAML we only have a Button and a TextBlock which will show possible errors or a message:

<UserControl x:Class="FileSaveDialogDemo.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">  
    <Canvas x:Name="LayoutRoot" Background="White">  
        <Button x:Name="btnSaveFile" Width="100" Height="20" 
                Content="Save File" Click="btnSaveFile_Click" 
                Canvas.Top="10" Canvas.Left="10"></Button> 
        <TextBlock x:Name="tblError" Canvas.Top="40" Canvas.Left="10"></TextBlock> 
    </Canvas> 
</UserControl> 

The interesting part comes in the code behind: 

using System;  
using System.IO;
using System.Windows;  
using System.Windows.Controls;  
using FileSaveDialogDemo.FilesServiceReference;  
 
namespace FileSaveDialogDemo  
{  
    public partial class MainPage : UserControl  
    {
        #region Fields  
        private SaveFileDialog dialog;
        #endregion  
 
        #region Constructors  
        public MainPage()  
        {  
            InitializeComponent();  
 
            this.dialog = new SaveFileDialog();  
 
            try 
            {  
                this.dialog.DefaultExt = ".txt";  
                this.dialog.Filter = "Text Files|*.txt|Log Files|*.log|All Files|*.*";  
                this.dialog.FilterIndex = 2;  
            }  
            catch ( Exception ex )  
            {  
                this.tblError.Text = "Error configuring SaveFileDialog: " + ex.Message;  
            }  
        }
        #endregion  
 
        #region Handlers  
        private void btnSaveFile_Click( object sender, RoutedEventArgs e )  
        {  
            bool? dialogResult = this.dialog.ShowDialog();  
 
            if ( dialogResult == true )  
            {  
                try 
                {  
                    FilesServiceReference.FilesClient fileClient  
                        = new FilesClient();  
                    fileClient.GetFileCompleted  
                        += new EventHandler<GetFileCompletedEventArgs>(  
                            fileClient_GetFileCompleted );  
                    fileClient.GetFileAsync();  
 
                    this.tblError.Text = "Getting file from the server...";  
                }  
                catch ( Exception ex )  
                {  
                    this.tblError.Text = "Error calling service: " + ex.Message;  
                }  
            }  
        }  
        void fileClient_GetFileCompleted( object sender, GetFileCompletedEventArgs e )  
        {  
            try 
            {  
                byte[] fileBytes = e.Result as byte[];  
 
                using ( Stream fs = ( Stream )this.dialog.OpenFile() )  
                {  
                    fs.Write( fileBytes, 0, fileBytes.Length );  
                    fs.Close();  
 
                    this.tblError.Text = "File successfully saved!";  
                }  
            }  
            catch ( Exception ex )  
            {  
                this.tblError.Text = "Error getting result: " + ex.Message;  
            }  
        }
        #endregion     
 
    }  

At first we need an instance of the SaveFileDialog class so we have created the following field:

private SaveFileDialog dialog; 

and have initialized it in the constructor:

this.dialog = new SaveFileDialog(); 

After that we've adjusted some of the properties of the SaveFileDialog object:

this.dialog.DefaultExt = ".txt";  
this.dialog.Filter = "Text Files|*.txt|Log Files|*.log|All Files|*.*";  
this.dialog.FilterIndex = 2; 

Let's describe each of the properties:

  • DefaultExt - the default extension is appended to the file name if no extension is written by the user or if the extension is not specified by the filter.
  • Filter - the filter specifies the file type options which the user has when saving the file. In our case the options will be:

Each option consists of name which will be displayed in the dropdown and a wildcard expression specifying the filter by which the files in the directory view will be filtered. In our case we have the following options:
    Text Files|*.txt
    Log Files|*.log
    All Files|*.*

All of them are separated by a vertical line.

Note that if the user does not write an extension it will be taken from the selected wildcard expression if it specifies a valid extension. For example if the user selects the first option a .txt extension will be added but if he/she selects the last option no extension will be added.

  • FilterIndex - the filter index specified the selected by default option. It is not zero based. In our case "Log Files" will be selected by default.

In the button click handler we call the ShowDialog method of the SaveFileDialog:

bool? dialogResult = this.dialog.ShowDialog(); 

After that we check if the returned result is true:

if (dialogResult == true

If the result is true we call a service in order to get a text file from the server.

In the Completed event handler of the service we just take the file as a byte array and write it to the stream returned by the OpenFile method of the SaveFileDialog:

using (Stream fs = (Stream)this.dialog.OpenFile())  
{  
    fs.Write(fileBytes, 0, fileBytes.Length);  

That's all, your users are now able to save file from the server on their computers.

Conclusion

 This article describes the use of the SaveFileDialog class in Silverlight. Any comments are welcome.


Subscribe

Comments

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Prakash on Mar 20, 2009 22:47
    Nice article. Sometimes, if I press the Escape key, or close the browser window while uploading images in Silverlight, I can see that half of the image is uploaded, and the rest is cut off. I can see the half image when I open it next time.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by enver on Mar 21, 2009 16:59
    nice article Nikolay, thank you.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by George on Mar 24, 2009 15:57
    Can I save canvas content to a image ?

    George
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Braulio (dbschemaeditor.com) on Apr 03, 2009 15:24

    Jeje the canvas save is something quite demand on SL2 (the only workaround available was to port all your drawing code to GDI+ and perform that render in the server).

    Until now I haven't read anything about saving canvas or exporting to image on SL3, let's hope the implement something (I think it's a must).

  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Apr 06, 2009 08:41
    George, I think that Braulio is right. I did not find solution for saving the content of a Canvas directy as an image. There is a kind of workaround where you send the XAML to a service and on the server you use WPF to convert it to an image and after that the service returns the image. But that's an ugly workaround beacuse another round trip to the server is needed.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by George on Apr 07, 2009 15:00
    Thanks :)
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Charles on Apr 09, 2009 09:16
    where can i get this save dialog dll
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Todd on Apr 17, 2009 22:59
    Silverlight 3 contains Bitmap APIs that WILL allow you to save the element tree to an image.
  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Apr 21, 2009 02:54
    Thanks for your comment Todd, can you please give a tip how we can save the element tree to an image. I was playing with the WriteableBitmap but did not find any solution.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Purva on Jun 24, 2009 10:25

    Hey guys,

    When i used the above code , in the button handler I am getting "Dialogs must be user-initiated." exception at the line 

    bool? dialogResult = this.dialog.ShowDialog();..        Any help on this?

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by sltester on Jul 15, 2009 23:54
    what does your service reference do?
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by sltester on Jul 15, 2009 23:56
    Actually what does it return?  A text file?
  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Jul 16, 2009 09:40
    Yes, it is a text file.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Braulio on Jul 17, 2009 22:58

    About saving canvas to PNG, compiled some bits from here and there in a solution

    http://geekswithblogs.net/braulio/archive/2009/07/12/export-canvas-to-png-and-save-it-in-your-local.aspx

    Thanks

      Braulio

     

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by sltester on Jul 22, 2009 21:04
    Do you know of a way to do this with a .zip file?  I am trying to zip multiple files in my webservice and return it to my Silverlight Web App to use the save file dialog.  I believe this is the best way to handle saving multiple files to the user's machine.  Am I correct
  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Jul 23, 2009 09:56
    sltester, the technique is the same with the zip file. It's about service implementation how you will put your files in a zip archive but it is beyond the scope of this article.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by sltester on Jul 23, 2009 17:27
    Thank you for your response nikolay,  I have accomplished zipping the files but am still lost on what to do with my zipped file and SaveFileDialog.  I have put multiple files into my zipped file using a "ZipFileStream" in my web service, do I return the "ZipFileStream" or the whole file? and then I would use e.Result as byte correct?
  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Jul 27, 2009 09:30

    Hi again, sltester,

    That's what I am doing in the service:

    [OperationContract]  
    public byte[] GetFile()  
    {  
        return File.ReadAllBytes( HttpContext.Current.Server.MapPath( "~/Files/text.zip" ) );  
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by sltester on Jul 27, 2009 17:15
    Thank you very much for all your help.  It is greatly appreciated and I have successfully used SaveFileDialog.
  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Jul 29, 2009 16:39

    Guys and Girls,

    Here I found another working solution for saving the XAML as a jpeg image:

    http://blog.blueboxes.co.uk/2009/07/21/rendering-xaml-to-a-jpeg-using-silverlight-3/

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by jakb on Aug 03, 2009 17:07
    I have an app displaying images from a file located in the Silverlight app but I can only upload a new image to the asp.net app - is there a way to allow read and write to a common file? 
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Prithwish on Aug 27, 2009 16:44
    How to download mp3 file using SaveFileDialog?
  • lemon

    RE: Using the SaveFileDialog in Silverlight 3


    posted by lemon on Oct 21, 2009 06:11

    hi ,I have the same question with purva,I want to know how to soluation it .Thanks.

    this question is :

     in the button handler I am getting "Dialogs must be user-initiated." exception at the line 

    bool? dialogResult = this.dialog.ShowDialog();

     

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by monica on Oct 28, 2009 21:25

    Hello

    I use safefiledialog and function well, but I need specific the route when I like saved the file (C:\namefile.pdf) and I cant, somebody know a method

  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Oct 29, 2009 17:14

    lemon, could you please send me the piece of your project where the error occurs so I'll be able to search for solution for your problem. My email is nraychev --- at --- completit.com

    monica, sorry but I can't find a solution for your problem. I don't see a property for specifying a default save file path.

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by swapprose on Oct 29, 2009 19:31
    Iam getting error like "dialog must be user intiated", I used the code in the similar way. I am reading xml values in the .net web service and in the completed event i am exporting into excel, there I m getting error for savefiledialog. please help me.
  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Oct 30, 2009 09:33

    Hi, swapprose.

    Try putting your code in the handler of a button click or somthing else that is user initiated.

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Sandeep on Nov 04, 2009 23:50
    how can we open the file just saved using this control ?
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Didier on Nov 15, 2009 21:35

    This is a great article and exactly what I was looking for.  I embedded the code in my silverlight 3 / expression Blend app.  I am able to see the file dialog.  However, I can not get the code to create the file.  I am unable to find the reference to FilesServiceReference.  Where can I find the DLL for this reference?

    Thanks in advance for your help,

    Didier

  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Nov 16, 2009 11:53

    Hi Didier,

    Here I uploaded the complete source project for this demo:

    FileSaveDialogDemo.zip

    You need to create your own service and update the service reference in the ServiceReferences.ClientConfig file. The project contains exemplary web service which you may modify and use.


    SilverlightShow editor: The source code has been added to the article.

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Balupad on Nov 16, 2009 12:37
    hi,
          It is look so nice.but i have a problem in the save dialog.I am not able to give the default file name in the save dialog.could please tell me how to apply the default file in the save dialog..
  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Nov 18, 2009 12:40
    Balupad, this seems to be impossible in the current release but we can expect the guys from Microsoft to add this feature in future releases.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Anish Sharma on Dec 13, 2009 20:21

    Hi Didier,

    I want to upload the image or a video file to a blob,I am able to browse it from my system but how should I approach to upload it into a blob using silverlight?

  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Dec 16, 2009 17:47

    Hi Anish Sharma,

    The SaveFileDialog's purpose is to download files and save them to user's computer. It's not for uploading files.

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Eugenio on Mar 15, 2010 16:17

    This sample does not work in Windows 7 with IE 8 because of UAC restrictions.

    I can't say to users to run as administrators. Any workaround?

    Thanks

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Jean on Apr 19, 2010 11:54

    Hi, may i know whether is there a way to do this with a .pdf file because i'm trying to download pdf files in my web service and return it to my Silverlight Web App to use the save file dialog?

     

     

  • nikolayraychev

    RE: Using the SaveFileDialog in Silverlight 3


    posted by nikolayraychev on Apr 20, 2010 10:40
    Yes, it's the same with all kind of files.
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by asdasd on Apr 20, 2010 13:29
    [OperationContract]
    public byte[] GetFile()
    {
    return File.ReadAllBytes( HttpContext.Current.Server.MapPath( "~/Files/text.zip" ) );
    }
  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by Amit on Jul 30, 2010 14:26

    Can SaveFileDialog be show at ViewModel.

    My scenario is like:  I am calling WCF service in Silverlight and in its asyn Callback i am trying to open SaveFileDialog box.

    It showing me "Dialogs must be user-initiated."

    any help

  • -_-

    RE: Using the SaveFileDialog in Silverlight 3


    posted by abc on Dec 13, 2010 23:07
    SaveFileDialog not working with silverlight 3
  • lnikolov

    RE: Using the SaveFileDialog in Silverlight 3


    posted by lnikolov on Dec 21, 2010 16:02

    abc, what exactly is not working with Silverlight 3?

  • lnikolov

    RE: Using the SaveFileDialog in Silverlight


    posted by lnikolov on Dec 22, 2010 18:31
    The article has been updated to the latest version of Silverlight and Visual Studio.
  • VladServitola

    Re: Using the SaveFileDialog in Silverlight


    posted by VladServitola on Sep 13, 2011 07:37
    Thanks! )) no problems at all with your tutorial ))
  • rajkaty

    Re: Using the SaveFileDialog in Silverlight


    posted by rajkaty on Dec 06, 2011 09:17

    How do I open the file from code that has been saved on the user(client) computer?

    My user saves it using SaevDialog box, now I want to automatyically open up after being saved. How to do that? I do not have complete file name coz' of Silverlight limitations. 

    Please suggest.


    Thanks

  • Meera

    Re: Using the SaveFileDialog in Silverlight


    posted by Meera on Aug 24, 2012 08:31

    How can we save and read pdf file in client side localy which is generated on server?

Add Comment

Login to comment:
  *      *