简体   繁体   English

如何将 XDocument 的 XML 内容保存为 .xml 文件?

[英]How can I save the XML contents of an XDocument as an .xml file?

I have an XDocument class with the XML contents already made.我有一个 XDocument class,其中已经制作了 XML 内容。 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.我基本上想打开一个 SaveFileDialog,让用户选择一个文件夹(不是文件),将内容保存为 .xml 文件。

I'm having some difficulty doing so:我这样做有一些困难:

a) How can I use the SaveFileDialog to prompt the user to select a folder? a) 如何使用 SaveFileDialog 提示用户到 select 文件夹? I've only been able to use it to get a user to select a file.我只能用它来让用户访问 select 一个文件。

b) How do I extract the chosen path from SaveFileDialog? b) 如何从 SaveFileDialog 中提取选定的路径?

c) Once I have the path, how can I save the contents of the XDocument? c) 有了路径后,如何保存 XDocument 的内容? There's a method called Save that requires a Stream - how do I build the stream using the path?有一个名为 Save 的方法需要 Stream - 如何使用路径构建 stream? (This might be a basic question, I have almost no IO experience) (这可能是个基本问题,我几乎没有IO经验)

a) You don't want to select a Folder, but a file name (Save* File *Dialog) a) 你不想 select 一个文件夹,而是一个文件名(Save* File *Dialog)

b) SaveFileDialog.FileName b) 保存文件对话框.文件名

c) Look at different overloads: you have XDocument.Save(string fileName). c) 查看不同的重载:您有 XDocument.Save(string fileName)。 No need to have a stream, you can have a fileName (oh, you got it in SaveFileDialog)不需要stream,你可以有一个文件名(哦,你在SaveFileDialog中得到它)

EDIT : you mean user can't change the name of the file?编辑:你的意思是用户不能更改文件名? then然后

a) FolderBrowserDialog a) 文件夹浏览器对话框

b) FolderBrowserDialog.SelectedPath b) FolderBrowserDialog.SelectedPath

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

( EDIT 2 : Path.Combine is more elegant in c) ). 编辑 2 :Path.Combine 在 c 中更优雅))。

A & B (sample code from duplicate question): A & B(来自重复问题的示例代码):

C (minimum code to save XDocument ): C(保存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); 

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:确保您将 SaveFileDialog 添加到您的表单并签署了 FileOk 事件(可以通过 SaveFileDialog 的属性完成),然后以下代码应该适用于您的:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM