简体   繁体   English

将文件保存在C#中

[英]Save the file in C#

I have a tree view and a button and a toolbox. 我有一个树状视图,一个按钮和一个工具箱。 I will create the tree by dragging and dropping items from toolbox. 我将通过从工具箱中拖放项目来创建树。 At the end, i will store the tree structure as an xml file. 最后,我将树结构存储为xml文件。 For this, when I click on the button, it prompts for save dialog and once the user select the path to store, I am able to save the xml file successfully. 为此,当我单击按钮时,它会提示“保存”对话框,并且一旦用户选择了存储路径,便能够成功保存xml文件。 Now, if I want to save the structure without opening the save dialog every time(whenever I make changes to tree structure) when I make changes(except first time) like in MS word, how can I achieve it? 现在,如果我想像在MS Word中那样进行更改(第一次更改除外)时,每次(无论我对树结构进行更改时)都没有打开保存对话框的情况下保存结构,如何实现?

Just save the file name you chose in the dialog in a variable. 只需将您在对话框中选择的文件名保存在变量中即可。 Next time check if you have the file name, if you do simply save the file. 下次检查是否具有文件名(如果只是保存文件)。

If you are "dragging and dropping" the SaveFileDialog on your form, the SaveFileDialog object will have the FileName set until you close the application. 如果要“拖放”表单上的SaveFileDialog,则在关闭应用程序之前,将设置FileName的FileName。 There is no need to save to a field in your forms class. 无需保存到表单类中的字段。 Though it is basically the same. 虽然基本相同。

    private SaveFileDialog saveFileDialog = null;

    private string GetFileName()
    {
        if (saveFileDialog.FileName != String.IsNullOrEmpty(saveFileDialog.FileName))
        {
            return saveFileDialog.FileName;
        }
        else
        {
            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                return saveFileDialog.FileName;
            }
            else
            {
                //throw exception or something similar
            }
        }
    }

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

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