Search code examples
c#wpfsavefiledialog

Save stream of savefiledialog in c#


In my wpf app I have an "Export" button that suppose to save some json file to chosen path.

I mean my question is how to write the file, let's say he has the path D:\somefile.json to the chosen location that the user chose from save dualog?

Here my code:

void Export_button_Click(object sender, RoutedEventArgs e)
{
        Stream myStream;
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        saveFileDialog1.Filter = "Json files (*.json)|*.json";
        saveFileDialog1.FilterIndex = 2;
        saveFileDialog1.RestoreDirectory = true;

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if ((myStream = saveFileDialog1.OpenFile()) != null)
            {
                // Code to write the stream goes here.
                myStream.Close();
            }
}

This should be something like:

Copy(StreamOf(D:\somefile.json),ChosenPath)


Solution

  •  SaveFileDialog sf = new SaveFileDialog();
     sf.Filter = "Json files (*.json)|*.json";
     sf.FilterIndex = 2;
     sf.RestoreDirectory = true;
     if (sf.ShowDialog() == DialogResult.OK)
     {                  
         System.IO.File.Copy(@"D:\somefile.json", sf.FileName, true);   
     }