6

I have an XDocument class with the XML contents already made. I basically want to open a SaveFileDialog, have the user choose a folder (not a file) in which to save the contents as an .xml file.

I'm having some difficulty doing so:

a) How can I use the SaveFileDialog to prompt the user to select a folder? I've only been able to use it to get a user to select a file.

b) How do I extract the chosen path from SaveFileDialog?

c) Once I have the path, how can I save the contents of the XDocument? There's a method called Save that requires a Stream - how do I build the stream using the path? (This might be a basic question, I have almost no IO experience)

Daniel
  • 2,944
  • 3
  • 22
  • 40
  • 1
    You are asking too many things in the same question. Split this into two questions. One regarding SaveFileDialog and one for saving the XDocument. – Anders Abel Apr 07 '12 at 19:31

3 Answers3

6

a) You don't want to select a Folder, but a file name (Save*File*Dialog)

b) SaveFileDialog.FileName

c) Look at different overloads : you have XDocument.Save(string fileName). No need to have a stream, you can have a fileName (oh, you got it in SaveFileDialog)

EDIT : you mean user can't change the name of the file ? then

a) FolderBrowserDialog

b) FolderBrowserDialog.SelectedPath

c) XDocument.Save(FolderBrowserDialog.SelectedPath + "/" + THENAMEOFYOURFILETHATUSERCANTCHANGE)

(EDIT 2 : Path.Combine is more elegant in c) ).

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
3

A & B (sample code from duplicate question):

C (minimum code to save XDocument):

XDocument document = new XDocument();
document.Add(new XElement("my_root"));
// Save(): there are 6 overloads; the 2nd one takes a path
document.Save(filePathFromSaveDialog); 
Community
  • 1
  • 1
JohnB
  • 18,046
  • 16
  • 98
  • 110
0

Make sure you added SaveFileDialog to your form and signed to FileOk event (can be done though SaveFileDialog's properties), then following code should work for your:

private void button1_Click(object sender, EventArgs e)
{
    // When user clicks button, show the dialog.
    saveFileDialog1.ShowDialog();
}

private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
    // Get file name.
    string name = saveFileDialog1.FileName;
    // Write to the file name selected.
    xDocumentYouHave.Save(name);
}
Andriy Buday
  • 1,959
  • 1
  • 17
  • 40