Qmars Emad
Qmars Emad

Reputation: 33

How To Get File Directory In C# And show in xml

this is my cod i want with this get all file in directory and end write all in xml file

  private void button3_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();

        string appPath = Path.GetDirectoryName(Application.ExecutablePath);

        string folder = appPath;//Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Archive\";
        string filter = "*.*";
        string[] files = Directory.GetFiles(folder, filter);
        foreach (string item in files)
        {

            string string1 = item;
            string string2 = appPath;
            string  result = string1.Replace(string2, "");
            MessageBox.Show(result);
            doc.LoadXml("<item><name>@" + result + " </name></item>");
            // Save the document to a file and auto-indent the output.
            using (XmlTextWriter writer = new XmlTextWriter("data.xml", null))

            {
                writer.Formatting = Formatting.Indented;
                doc.Save(writer);
                writer.Close();
            }
        }
    }

with this code i get my file in directory and remove path for example C://folder1/folder2/bin/app.exe to app.exe its okay but in the end in xml just write one file XML Result

<?xml version="1.0"?>
<item>
  <name>@\WindowsFormsApplication8.vshost.exe.manifest </name>
</item>

Upvotes: 2

Views: 1942

Answers (3)

Qmars Emad
Qmars Emad

Reputation: 33

thanks for best answers. in my directory too i have 3 folder and There are more files in any folder ,i want any files in folders write in my xml For Example

<Items>
  <Item>\ConsoleApplication1.exe</Item>
  <Item>\ConsoleApplication1.exe.config</Item>
  <Item>\ConsoleApplication1.pdb</Item>
  <Item>\ConsoleApplication1.vshost.exe</Item>
  <Item>\ConsoleApplication1.vshost.exe.config</Item>
<Item>..folder1\gold.dll</Item>
<Item>..images\exit.png</Item>

Upvotes: 0

Bilal Fazlani
Bilal Fazlani

Reputation: 6967

You are overwriting your items.

Here's the code that will write a proper xml:

        XmlDocument doc = new XmlDocument();

        string appPath = Directory.GetCurrentDirectory();

        string folder = appPath;
        string filter = "*.*";
        string[] files = Directory.GetFiles(folder, filter);

        using (XmlTextWriter writer = new XmlTextWriter("data.xml", null))
        {

            writer.WriteStartDocument();

            writer.WriteStartElement("Items");

            foreach (string item in files)
            {
                string string1 = item;
                string string2 = appPath;
                string result = string1.Replace(string2, "");

                writer.WriteElementString("Item","", result);

                Console.WriteLine(result);

                writer.Formatting = Formatting.Indented;
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();

            writer.Close();
            doc.Save(writer);
        }

And here's the sample xml,

<?xml version="1.0"?>
<Items>
  <Item>\ConsoleApplication1.exe</Item>
  <Item>\ConsoleApplication1.exe.config</Item>
  <Item>\ConsoleApplication1.pdb</Item>
  <Item>\ConsoleApplication1.vshost.exe</Item>
  <Item>\ConsoleApplication1.vshost.exe.config</Item>
  <Item>\ConsoleApplication1.vshost.exe.manifest</Item>
  <Item>\data.xml</Item>
</Items>

Upvotes: 0

Ben Cottrell
Ben Cottrell

Reputation: 6120

Here:

        doc.LoadXml("<item><name>@" + result + " </name></item>");

Every time your loop repeats, you're overwriting all of the XML in your XmlDocument.

If you want to use XmlDocument, try this instead, although there are other (Cleaner) ways to output XML.

        var doc = new XmlDocument();
        var root = doc.AppendChild(doc.CreateElement("Item"));

        foreach (var item in files)
        {
            var name = root.AppendChild(doc.CreateElement("Name"));
            name.InnerText = item;
        }


        var xmlWriterSettings = new XmlWriterSettings { Indent = true };
        using (var writer = XmlWriter.Create("data.xml", xmlWriterSettings))
        {
            doc.Save(writer);
        }

Using XmlSerialiser (cleaner C# code than XDocument):

public class Program
{
    [XmlType("Item")]
    public class Item
    {
        [XmlElement("Name")]
        public string[] Files { get; set; }
    }

    static string SerialiseToXml<T>(T obj, bool isFormatted = false)
    {
        var ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        var stringBuilder = new StringBuilder();
        var xmlWriterSettings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = isFormatted };
        using (var xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
        {
            var serializer = new XmlSerializer(obj.GetType());
            serializer.Serialize(xmlWriter, obj, ns);
            return stringBuilder.ToString();
        }
    }

    static void Main(string[] args)
    {
        string[] files = {"Apple.txt", "Orange.exe", "Pear.docx", "Banana.xml", "Papaya.xls", "Passionfruit.cs"};

        var item = new Item {Files = files};
        var xml = SerialiseToXml(item, true);

        Console.WriteLine(xml);
    }
}

Upvotes: 1

Related Questions