I'm trying to write an XML file in C# using **XmlWriter** in a recursive function. The file is supposed to contain every single folder in a given directory as well as every subfolder and file. 

I'm having some trouble in trying to write special characters in the XML file, it's constantly giving me the error that 

> 
> I can't use characters such as '&', '/', '-', '.', ' ' etc.
> 
> 
> 

And even numbers aren't working. I have tried finding similar questions to this problem and no solution helped me, I have tried replacing the folder and/or file string name that consists of special characters and escaping them using "&amp ;", "&quot ;", "&apos ;" etc. But that isn't working either. It just gives me an error that I can't use '&'.

```
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml;

namespace XMLgenerator
{
    public class Generator
    {
        public void write(string Dir, XmlWriter writer)
        {
            try
            {
                writer.WriteStartElement("Folders");
                 foreach (string s in Directory.GetDirectories(Dir))
              {
                    string[] splitter = s.Split('\\');
                    string ss = splitter[splitter.Length - 1];
                    string ssxml = XmlConvert.EncodeLocalName(ss);
                        writer.WriteStartElement("Folder");
                    writer.WriteAttributeString("name", ssxml);

                    foreach (string f in Directory.GetFiles(s))
                    {
                        string fxml = XmlConvert.EncodeLocalName(f);
                        FileInfo fi = new FileInfo(f);
                        long length =  fi.Length;
                        writer.WriteElementString(fxml, length.ToString());
                    }
                    writer.WriteEndElement();
                    write(s,writer);
                }
                writer.WriteEndElement();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
        }
        // Method for creating an XML file and also getting directories and files. File name and dir path are parametres
        public void generateContent(string Dir)
            {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Encoding = new UTF8Encoding();
            using (XmlWriter writer = XmlWriter.Create("test.xml", xws))
            {
                writer.WriteStartDocument();
                write(Dir,writer);
                writer.WriteEndDocument();
            }

            }
        }
    }

```