views:

60

answers:

4

I want to serialize an object into an xml and I want the filename of the xml to be random as following

636211ad-ef28-47b9-aa60-207d3fbb9580.xml

fc3b491e5-59ac-4f6a-81e5-27e971b903ed.xml

I am just curious on how to do such thing?

+2  A: 

Look at System.Guid.

Guid guid = System.Guid.NewGuid();
Anthony Pegram
+1  A: 

Good description of serialization with some encapsulation can be found here The name seems to be a Guid, so just create a new guid, convert it to text and use that as the filename.

Development 4.0
@Development: I almost downvoted you. The OP didn't ask how to do serialization, only how to get the file names the way he liked.
John Saunders
+2  A: 
var fileName = String.Format("{0}.xml", System.Guid.NewGuid().ToString());
used2could
+3  A: 

Here is an example with a sample class.

public class TestSerialize
{
    public string Test1;
    public int Test2;
}

class Program
{      
    [STAThread]
    static void Main()
    {
        var serializer = new XmlSerializer(typeof(TestSerialize));
        using (XmlWriter writer = XmlWriter.Create(Guid.NewGuid() + ".xml"))
        {                
            serializer.Serialize(writer, new TestSerialize() { Test1 = "hello", Test2 = 5 });
        }

        Console.ReadLine();
    }
}
Matt Dearing
@Matt: downvoting you for several reasons: 1) The XML Serializer ignores the `Serializable` attribute. 2) `new XmlTextWriter()` is deprecated as of .NET 2.0. Use `XmlWriter.Create()` instead. 3) Did the OP say _anything_ about ASCII encoding?
John Saunders
@John I updated my answer to reflect your comments. I was unaware of XmlWriter.Create(). I will make sure to use it from now on. Thank you for the comment.
Matt Dearing
@Matt: I'll reverse the downvote, but I suggest you use `XmlWriter.Create` and not `XmlTextWriter.Create`.
John Saunders