我想知道如何将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);
}
}
}
}
但是,这仍然是调用我的旧保存功能,它告诉我的程序保存在桌面上。有没有办法可以将我保存的文件位置传递给我的保存功能?
答案 0 :(得分:1)
答案 1 :(得分: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);
}