Gratzy
Gratzy

Reputation: 2908

Deserializing an xml file into an object

I'm working in within a windows service I created. Code works fine on my dev box but when I deploy the code to a server it's not able to find the xml file to deserialize. The xml files are created in C:\ProgramData\AppName\Filequeue

In the object I created a helper method:

    public T Deserialize<T>(string input) where T : class
    {
        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

        using (var reader = XmlReader.Create(input))
        {
            return (T)ser.Deserialize(reader);
        }
    }

I then create an object using an impersonating object and attempt to read the file:

 using (var impersonation = new ImpersonatedUser(AdminName, Domain, ADPass))
 {    
    oMailer = (MailQueue) oMailer.Deserialize<MailQueue>(szFileName);
 }

I get a file name not found error when it tries to load the file into the object in the Deserialize() object. I'm guessing the impersonation isn't flowing into the object that I'm attempting to load.

If I try to load in a text reader under the impersonation I can see the file just fine. So I know the file exists and is seen by the program.

Anyone have an idea what is going on?

Upvotes: 0

Views: 297

Answers (1)

Gratzy
Gratzy

Reputation: 2908

I moved the file reader code to under the method containing impersonation. Then created a stand along object:

public class Serializer
{
    public T Deserialize<T>(string input) where T : class
    {
        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

        using (StringReader sr = new StringReader(input))
        {
            return (T)ser.Deserialize(sr);
        }
    }

    public string Serialize<T>(T ObjectToSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

        using (StringWriter textWriter = new StringWriter())
        {
            xmlSerializer.Serialize(textWriter, ObjectToSerialize);
            return textWriter.ToString();
        }
    }
}

Then I was able to load the XML then load and deserialize it by:

using (impersonation...)
{
   var reader = File.ReadAllText(szFileName);
   oMailer =  ser.Deserialize<MailQueue>(reader);
}

I'm still confused on why the impersonation doesn't seem to inherit into an object that is created within the impersonation? But I don't have time to deal with that now...

Upvotes: 1

Related Questions