1

我想知道您如何将winform中的文件保存到目标位置,而无需在该位置进行硬编码。

现在,我的保存方法如下所示:

public void GenereateSettingsFile(List<Node> nodeList)
{
    string filePath = "Desktop\\Save.xml";
    _rootNode.RemoveChild(_userNode);

    _userNode = _xmlDoc.CreateElement("Display_Settings");
    _rootNode.AppendChild(_userNode);

    foreach (Node n in nodeList)
    {
        foreach (XmlElement e in n.GenerateXML(_xmlDoc))
        {

            _userNode.AppendChild(e);
        }
    }

    _xmlDoc.Save(filePath);
}

public void SaveXML(string location)
{
    _xmlDoc.Save(location);
}

当我像这样点击保存按钮时调用它:

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
    foo.GenereateSettingsFile(_nodeList);
}

现在,使用我的另存为功能,我得到了它,因此会弹出一个新窗口,我可以浏览到我希望使用以下代码保存文件的位置:

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
    using (SaveFileDialog dialog = new SaveFileDialog())
    {
        dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        dialog.FilterIndex = 2;
        dialog.RestoreDirectory = true;

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            // Can use dialog.FileName
            using (Stream stream = dialog.OpenFile())
            {
                // Save data
                inmo.GenereateSettingsFile(_nodeList);
            }
        }
    }
}

但是,这仍然在调用我的旧保存函数,它告诉我的程序保存在桌面中。有没有办法可以将我的另存为窗口生成的文件位置传递给我的保存功能?

4

2 回答 2

1

尝试

dialog.InitialDirectory = myPreferredDirectory;

有关详细信息,请参阅SaveFileDialog.InitialDirectory

于 2013-05-22T13:55:09.383 回答
1

只需提升filePath为 的参数即可GenereateSettingsFile

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
    using (SaveFileDialog dialog = new SaveFileDialog())
    {
        dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        dialog.FilterIndex = 2;
        dialog.RestoreDirectory = true;

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            // Can use dialog.FileName
            //using (Stream stream = dialog.OpenFile())
            //{
            // Save data
            inmo.GenereateSettingsFile(_nodeList, dialog.FileName);
            //}
        }
    }
}

public void GenereateSettingsFile(List<Node> nodeList, string filePath)
{
    //string filePath = "Desktop\\Save.xml";
    _rootNode.RemoveChild(_userNode);

    _userNode = _xmlDoc.CreateElement("Display_Settings");
    _rootNode.AppendChild(_userNode);

    foreach (Node n in nodeList)
    {
        foreach (XmlElement e in n.GenerateXML(_xmlDoc))
        {

            _userNode.AppendChild(e);
        }
    }

    _xmlDoc.Save(filePath);
}
于 2013-05-22T14:06:29.480 回答