Monday, March 19, 2012

Getting all file names in directory and saving as XML using C#



Now am going to explain reading all file name in the directory and save the file name in a xml format .To read the file names in a directory is a file system task so include using System.IO; name space to your console application.
Get files from directory
 
To get all file names in the directory use the Method Directory.GetFiles returns string array with files names.
 Syntax :
String[] files = Directory.GetFiles(“<filepath>”);

To get the files with specified extension the use the second argument of Directory.GetFiles method. Syntax is as follows :

string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp");

It will return all file names in the directory C:\Mydir with file extension .bmp.
Get files from directory (including all subdirectories)
To get files from directory with all its subdirectories pass the third argument of Directory.GetFiles method.
Syntax :
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp",
                                        SearchOption.AllDirectories);
 
The following program will explain you to get all files which extension .pdf in D:\BlogerDir and saving as the xml file.
D:\ BlogerDir has the following directory structure :

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace FileConsile
{
   public class CreteXML
    {
        static void Main(string[] args)
        {
            //Getting all the files in the D:\BlogerDir with extension .pdf
            String[] files = Directory.GetFiles(@"D:\BlogerDir", "*.pdf", SearchOption.AllDirectories);
            //Declaring a xmldocument
            XmlDocument doc = new XmlDocument();
            //creating a Files node in the xmldocument
            XmlNode FilesNode = doc.CreateElement("Files");
            doc.AppendChild(FilesNode);
        
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo info = new FileInfo(files[i]);
                string name = files[i].ToString();
                XmlNode InfoNode = doc.CreateElement("File");
                XmlNode nameNode = doc.CreateElement("Name");
                nameNode.InnerText = name;
                InfoNode.AppendChild(nameNode);

                XmlNode sizeNode = doc.CreateElement("Size");
                sizeNode.InnerText = info.Length.ToString();
                InfoNode.AppendChild(sizeNode);

              
                FilesNode.AppendChild(InfoNode);
            }
         
            //saving the xml document in the path D:\MyXml.xml
            doc.Save(@"D:\MyXml.xml");
         
          Console.WriteLine(doc.InnerXml.ToString());
          Console.ReadLine();
        }
    }
}

Out put :





 


No comments:

Post a Comment