C# xml 에 쓰고 읽기

기본 적인 using 추가

 using System.Xml;

쓰기 부분

 
private void SaveXML()
{
    string sFilePath = System.IO.Directory.GetCurrentDirectory();
 
    try
    {
	XmlWriterSettings settings = new XmlWriterSettings();
	settings.Indent = true;
	settings.NewLineOnAttributes = true;
	XmlWriter xmlWriter = XmlWriter.Create(sFilePath + "/config.xml");
	xmlWriter.WriteStartDocument();
 
	xmlWriter.WriteStartElement("root");
	xmlWriter.WriteElementString("IP", "192.168.100.136");
	xmlWriter.WriteElementString("PORT", "3333");
	xmlWriter.WriteEndDocument();
 
	xmlWriter.Flush();
	xmlWriter.Close();
    }
    catch (Exception ex)
    {
	MessageBox.Show(ex.ToString());
    }
}

읽어오기 부분

private void LoadXML()
{
    string strIP = string.Empty;
    string strPORT = string.Empty;
 
    string sFilePath = System.IO.Directory.GetCurrentDirectory();
 
    try
    {
	if (File.Exists(sFilePath + "/config.xml")) // 파일 유무 검사
	{
	    XmlTextReader xmlReadData = new XmlTextReader(sFilePath + "/config.xml");
 
	    while (xmlReadData.Read())
	    {
		if (xmlReadData.NodeType == XmlNodeType.Element)
		{
		    switch (xmlReadData.Name.ToUpper().Trim())
		    {
			case "IP": strIP = xmlReadData.ReadString().ToString().Trim(); break;
			case "PORT": strPORT = xmlReadData.ReadString().ToString().Trim(); break;
		    }
		}
	    }
	    xmlReadData.Close();
 
	    textBox1.Text = strIP;
	    textBox2.Text = strPORT;
	}
	else // xml 파일 미존재 시
	{                    
	    SaveXML();
	}
    }
    catch (Exception ex)
    {
	MessageBox.Show(ex.ToString());
    }
}

실행 결과

xml