views:

402

answers:

4
+3  Q: 

How to serialize?

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        // Get all files in Documents
        List<string> dirs = FileHelper.GetFilesRecursive("S:\\bob.smith\\");
        foreach (string p in dirs)
        {
            Console.WriteLine(p);
        }
        // Write count
        Console.WriteLine("Count: {0}", dirs.Count);
        Console.Read();
    }
}

static class FileHelper
{
    public static List<string> GetFilesRecursive(string b)
    {
        // 1.
        // Store results in the file results list.
        List<string> result = new List<string>();

        // 2.
        // Store a stack of our directories.
        Stack<string> stack = new Stack<string>();

        // 3.
        // Add initial directory.
        stack.Push(b);

        // 4.
        // Continue while there are directories to process
        while (stack.Count > 0)
        {
            // A.
            // Get top directory
            string dir = stack.Pop();

            try
            {
                // B
                // Add all files at this directory to the result List.
                result.AddRange(Directory.GetFiles(dir, "*.*"));

                // C
                // Add all directories at this directory.
                foreach (string dn in Directory.GetDirectories(dir))
                {
                    stack.Push(dn);
                }
            }
            catch
            {
                // D
                // Could not open the directory
            }
        }
        return result;
        var k = "";
        result = k;
    }
}

This is my code. I am trying to serialize the result to an XML file (i thought by passing it to a var, i could use that variable to serialize). I'm at wits' end. Please someone help.

weirdly for some reason i can't add comments--in response, yes i have gone over endless tutorials about serialization. i'm a complete newbie at this stuff and frankly put, these tutorials have been unhelpful for the large part b/c i'm not able to put this function and serializaton together. at this point, i'm looking for a solution as i'm about to seriously break something out of frustration.

+3  A: 

If you simply want to output the contents of the dirs list, it's probably easiest using an XmlWriter:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(@"c:\path\filename.xml", settings))
{
    writer.WriteStartElement("dirs");
    dirs.ForEach(d => writer.WriteElementString("dir", d));
    writer.WriteEndElement(); // dirs
}

The result will look like this:

<?xml version="1.0" encoding="utf-16"?>
<dirs>
  <dir>c:\</dir>
  <dir>c:\Program Files</dir>
  ...
</dirs>

Note that this might not be what is generally meant when talking about serialization in .NET, since it amongst other things does not contain information about what type of object that contained the data, so you can not use this to deserialize the xml data into a List using the available serialization mechanisms in the framework.

Update

If you instead want to do it more "framework-style", you can use the BinaryFormatter:

// serialize the object to disk
BinaryFormatter formatter = new BinaryFormatter();
using (Stream stream = File.OpenWrite(@"c:\temp\dirlist.data"))
{
    formatter.Serialize(stream, dirs);
}

// at some other point, when you want to deserialize
BinaryFormatter formatter = new BinaryFormatter();
List<string> dirList;
using (Stream stream = File.OpenRead(@"c:\temp\dirlist.data"))
{
    dirList = (List<string>)formatter.Deserialize(stream);
}

In this case you will get a binary file on disk that makes little sense in a text editor (but it looks something like this; I have introduced some line breaks to make it more "readable"):

ÿÿÿÿ          System.Collections.Generic.List`1[[System.String, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]   
_items_size_version                       c:\   c:\Program Files
Fredrik Mörk
+2  A: 

I do not wish to sound mean, but it seems from your question that you're missing some very important and fundamental concepts to do with serialisation.

This tutorial might be a good place to start with serialisation. Try this out, and if you've questions then feel free to post them here on SO.

Hope this helps,

Binary Worrier
David, you thought the tutorial was unhelpful, or that the asker wasn't missing fundmental concepts to do with serialisation? It is never my intention to be mean when providing answers, and to be honest I don't think this is the case here. However in light of your comments I've changed the wording on this answer. Can you let me know if you still think it's mean? If so I shall delete the answer. Thanks :)
Binary Worrier
Based upon your edit, now I can see your intentions. I have taken away my down vote. Thank you for the update.
David Yancey
+1  A: 

On a side note, you could've got all the files across all sub folders using

Directory.GetFiles(@"S:\\bob.smith\\", "*.*", SearchOption.AllDirectories)
Vasu Balakrishnan
+6  A: 

You can use the XmlSerializer:

using System.Xml.Serialization;

static void Main()
    {
        // Get all files in Documents
        List<string> dirs = FileHelper.GetFilesRecursive(@"S:\\bob.smith\\");

        XmlSerializer x = new XmlSerializer(dirs.GetType());
        x.Serialize(Console.Out, dirs);



        Console.Read();
    }
Jason Heine
very nice solution.
J.W.