Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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();
    }
like image 106
CodeLikeBeaker Avatar answered Apr 10 '26 21:04

CodeLikeBeaker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!