[英]Winform saveas file location
I'm wondering how you got about saving a file in winform to the target location without having to hard code in the location. 我想知道您如何在Winform中将文件保存到目标位置而不必在该位置进行硬编码。
Right now, my save methods look like this: 现在,我的保存方法如下所示:
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);
}
This is called when I hit the save button like so: 当我按下“保存”按钮时,将调用此命令,如下所示:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
foo.GenereateSettingsFile(_nodeList);
}
Now, with my save as function I've got it so a new window pops up and I can browse to my location where I wish to save my file with this code: 现在,有了我的另存为功能,就可以弹出一个新窗口,然后浏览至我希望使用以下代码保存文件的位置:
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);
}
}
}
}
But, this is still calling my old save function which is telling my program to save in the desktop. 但是,这仍在调用我的旧保存功能,该功能告诉我的程序保存在桌面中。 Is there a way I can pass in the file location my save as window generates to my save function? 有什么方法可以将“我的另存为”窗口生成的文件位置传递给我的保存功能?
Try 尝试
dialog.InitialDirectory = myPreferredDirectory;
See SaveFileDialog.InitialDirectory for more info 有关更多信息,请参见SaveFileDialog.InitialDirectory 。
Just promote filePath
to be a parameter of GenereateSettingsFile
. 只需将filePath
提升为GenereateSettingsFile
的参数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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.