To tackle the problem you have what you need to do are the following steps.
To save the data in an xml:
Create a class that contains the data
Serialize the class
Save the serialized in a file
To recover the data:
Read and deserialize the file
Use the data
For example to save the data of your email you can use this class:
public class EmailData
{
public string MailTo { get; set; }
public string MailFrom { get; set; }
public int Port { get; set; }
public SmtpDeliveryMethod SmtpDeliveryMethod { get; set; }
public bool UseDefaultCredentials { get; set; }
public string Host { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
To serialize and deserialize objects you can use these extensions that I created:
public static class SerializerExtensions
{
public static void SerializarYGuardar(this object value, string ruta)
{
try
{
var xmlserializer = new XmlSerializer(value.GetType());
var stringWriter = new StringWriter();
using (XmlWriter writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, value);
StreamWriter strWr = File.CreateText(ruta);
strWr.Write(stringWriter);
strWr.Close();
strWr.Dispose();
}
}
catch (Exception ex)
{
throw new Exception("Se ha producido un error", ex);
}
}
public static T DesSerialize<T>(string rutafichero)
{
try
{
using (StreamReader streamRead = new StreamReader(rutafichero))
{
var xmlserializer = new XmlSerializer(typeof(T));
object obj = xmlserializer.Deserialize(streamRead);
if (obj is T)
return (T)obj;
else
throw new Exception("El objeto deserializado no es del tipo indicado");
}
}
catch (Exception ex)
{
throw new Exception("Ha ocurrido un error:", ex);
}
}
}
And an example of all this working would be:
class Program
{
static void Main(string[] args)
{
string rutaFichero = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "correo.xml");
EmailData emData = new ConsoleApplication2.EmailData()
{
Body = "mensaje...",
Host = "el host",
MailFrom = "[email protected]",
MailTo = "[email protected]",
Port = 22,
SmtpDeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
Subject = "subject",
UseDefaultCredentials = false
};
emData.SerializarYGuardar(rutaFichero);
EmailData result = SerializerExtensions.DesSerialize<EmailData>(rutaFichero);
}
}
After doing EmailData result = SerializerExtensions.DesSerialize<EmailData>(rutaFichero);
you will already have the data loaded so you can fill in your email with them.