-
Save files using c#
Hey,
I am having a problem with saving a file using c#. I am using the following code to save a xml file. I want the file to be saved right next to where the .exe file is. The following works most of the time, but if I use a SaveFileDialog anywhere else in the program, the path that I set there is used when saved the settings file as well and I cant understand why. Any ideas on why it is happending?
Code:
private void saveSettings()
{
string output = "<?xml version=\"1.0\" encoding='UTF-8'?>\n";
output += "<Settings>\n";
output += "\t<fps>" + m_fps.ToString() + "</fps>\n";
output += "\t<pivSize>" + m_pivotSize.ToString() + "</pivSize>\n";
output += "\t<rectLineWidth>" + m_rectLineWidth.ToString() + "</rectLineWidth>\n";
output += "\t<vertexLineWidth>" + m_vertexLineWidth.ToString() + "</vertexLineWidth>\n";
output += "\t<vertexSize>" + m_vertexSize.ToString() + "</vertexSize>\n";
output += "\t<makeHeader>" + m_makeHeaderFile.ToString() + "</makeHeader>\n";
output += "\t<headerFilePath>" + m_headerFilePath + "</headerFilePath>\n";
output += "</Settings>";
// Write the whole thing
TextWriter tw = new StreamWriter("Settings.xml");
tw.WriteLine(output);
tw.Close();
}
Regards,
-
SaveFileDialog changes current directory to the new one, look at the RestoreDirectory property is you want to disable this behavior...
Or take the Application.StartupPath property at the startup of the Application and use the fully qualified path when you create your StreamWriter
-
Thanks, that solved my problem
-
I use AppDomain.CurrentDomain.BaseDirectory to achieve the path to the exe file. Also there are some very nice XML helpers built into .net which you could use to build your settings file.
Code:
private void saveSettings()
{
XmlWriterSettings appearance = new XmlWriterSettings();
appearance.Indent = true;
XmlWriter xml = XmlWriter.Create(AppDomain.CurrentDomain.BaseDirectory + "Settings.xml", appearance);
xml.WriteStartDocument();
xml.WriteStartElement("Settings");
xml.WriteElementString("fps", m_fps.ToString());
xml.WriteElementString("pivSize", m_pivotSize.ToString());
xml.WriteElementString("rectLineWidth", m_rectLineWidth.ToString());
xml.WriteElementString("vertexLineWidth", m_vertexLineWidth.ToString());
xml.WriteElementString("vertexSize", m_vertexSize.ToString());
xml.WriteElementString("makeHeader", m_makeHeaderFile.ToString());
xml.WriteElementString("headerFilePath", m_headerFilePath);
xml.WriteEndElement();
xml.WriteEndDocument();
xml.Flush();
xml.Close();
}
-
I knew c# must have some nice xml functions. Thanks for sharing
-
Or you could use:
Code:
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);