遍歷指定文件夾中的文件,讀取MSN格式的XML文件

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

namespace DocumentUtility
{
    /// <summary>
    /// DirectoryProc
    /// </summary>
    public class DocumentUtility
    {
        #region parameter define
        //Searched directories's path list
        //public ArrayList DirectoriesPathList = null;
        //Searched directories's path list
        //public ArrayList FilesPathList = null;
        //The searched target directory path
        private string strTargetDirectoryPath = "";
        //Error Message
        public string strErrorMsg = "";
        //Respond content
        public string strRespondContent = "";

        #region read MSN XML file's parameter define
        //read name flag
        private bool blnAToBFlag = false;
        #endregion

        #endregion

        #region DocumentUtility
        /// <summary>
        /// DocumentUtility
        /// </summary>
        public DocumentUtility()
        {
            //SetCommand("/listdirpath|D://TestData//MSN Collection|TestDir");

            //SetCommand("/listalldirpath|D://TestData//MSN Collection//TestDir");

            //SetCommand("/listfiles|D://TestData//MSN Collection//TestDir|*.xml");

            //SetCommand("/getxmlfile|D://TestData//MSN Collection//TestDir//History//TestMSNMessage.xml");

            //ParseDirectory("D://TestData//MSN Collection", "*.xml");
        }
        #endregion

        #region SetCommand
        /// <summary>
        /// DirectoryProc Test.
        /// </summary>
        public void SetCommand(string strCommand)
        {
            GetCommand(strCommand);
        }
        #endregion

        #region SearchDirectory
        /// <summary>
        /// Search directory method。
        ///
        /// strDirectoryPath:The current target searched directory path.
        /// strSearchedDirectoryName:The searched directory's name.
        /// </summary>
        private void SearchDirectory(string strDirectoryPath, string strSearchedDirectoryName)
        {
            string[] Directories = Directory.GetDirectories(strDirectoryPath);
            IEnumerator itorDirs = Directories.GetEnumerator();
            while (itorDirs.MoveNext())
            {
                string strDir = (string)itorDirs.Current;
                string strTargetDirName = (string)strDir.Split('//').GetValue(strDir.Split('//').Length - 1);
                if (strTargetDirName == strSearchedDirectoryName)
                {
                    //DirectoriesPathList.Add(strDir);
                    strRespondContent += strDir + "/r/n";
                }
                else if (strTargetDirName.Length > strSearchedDirectoryName.Length)
                {
                    strTargetDirName = strTargetDirName.Substring(0, strSearchedDirectoryName.Length);
                    if (strTargetDirName == strSearchedDirectoryName)
                    {
                        //DirectoriesPathList.Add(strDir);
                        strRespondContent += strDir + "/r/n";
                    }
                }
                SearchDirectory(strDir, strSearchedDirectoryName);
            }
        }
        #endregion

        #region ParseDirectory
        /// <summary>
        /// Parse Directory
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="strFilter"></param>
        protected void ParseDirectory(string strPath, string strFilter)
        {
            string[] dirs = Directory.GetDirectories(strPath);
            IEnumerator itorDirs = dirs.GetEnumerator();
            while (itorDirs.MoveNext())
            {
                string strDir = (string)itorDirs.Current;
                ParseDirectory(strDir, strFilter);
            }

            string[] files = Directory.GetFiles(strPath, strFilter);
            if (files.Length > 0)
            {
                IEnumerator itorFiles = files.GetEnumerator();
                while (itorFiles.MoveNext())
                {
                    string strFile = (string)itorFiles.Current;
                    //DirectoriesPathList.Add(strFile);
                }
            }
        }
        #endregion

        #region GetFilesPath
        /// <summary>
        /// Get Files's Path
        ///
        /// strTargetDirectory:The target directory's path.
        /// strFileType:The file's extend name.
        /// </summary>
        private ArrayList GetFilesPath(string strTargetDirectory, string strFileFilter)
        {
            ArrayList arFilesPathList = null;

            if (Directory.Exists(strTargetDirectory))
            {
                DirectoryInfo dir = new DirectoryInfo(strTargetDirectory);
                FileInfo[] files;
                files = dir.GetFiles(strFileFilter);

                if (files.Length > 0)
                    arFilesPathList = new ArrayList();

                for (int cnt = 0; cnt < files.Length; cnt++)
                {
                    arFilesPathList.Add(files[cnt].Name + "|" + files[cnt].LastWriteTime.ToString() + "|" + (files[cnt].Length / 1024 + 1).ToString() + "K");
                }
            }

            return arFilesPathList;
        }
        #endregion

        #region ReadFile
        /// <summary>
        /// Read File
        ///
        /// strTargetFilePath:The target file's path.
        /// strFileContent:The file's content.
        /// </summary>
        private bool ReadFile(string strTargetFilePath, ref string strFileContent)
        {
            bool blnReadFlag = true;
            FileStream fs;

            if (File.Exists(strTargetFilePath))
            {
                try
                {
                    fs = File.OpenRead(strTargetFilePath);
                    byte[] b = new byte[1024];
                    UTF8Encoding temp = new UTF8Encoding(true);
                    while (fs.Read(b, 0, b.Length) > 0)
                    {
                        strFileContent += temp.GetString(b);
                    }
                }
                catch (System.IO.IOException e)
                {
                    blnReadFlag = false;
                    throw e;
                }
            }
            else
            {
                blnReadFlag = false;
            }

            return blnReadFlag;
        }
        #endregion

        #region ReadXMLFileFromNode
        public void ReadXMLFile(string strXMLFilePath)
        {
            XmlTextReader reader = new XmlTextReader(strXMLFilePath);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            XmlNode xnod = xmlDoc.DocumentElement;
            XmlNamedNodeMap mapAttributes = xnod.Attributes;
            ReadXMLFileFromNode(xnod, 1);

            reader.Close();
            xmlDoc.RemoveAll();
            reader = null;
            xmlDoc = null;
        }
        #endregion

        #region ReadXMLFileFromNode
        private void ReadXMLFileFromNode(XmlNode xnod, Int32 intLevel)
        {
            //intLevel depth control
            XmlNode xnodWorking;
            //Get attributes from node
            if (xnod.NodeType == XmlNodeType.Element)
            {
                XmlNamedNodeMap mapAttributes = xnod.Attributes;
                //get attributes and value
                foreach (XmlNode xnodAttribute in mapAttributes)
                {
                    Console.Write(xnodAttribute.Name + ":" + xnodAttribute.Value + ":" + xnod.InnerText);
                }
                //check
                if (xnod.HasChildNodes)
                {
                    xnodWorking = xnod.FirstChild;

                    while (xnodWorking != null)
                    {
                        ReadXMLFileFromNode(xnodWorking, intLevel + 1);
                        xnodWorking = xnodWorking.NextSibling;
                    }
                }
            }
        }
        #endregion

        #region GetCommand
        /// <summary>
        /// Get Command
        /// </summary>
        /// <param name="strCommand"></param>
        private void GetCommand(string strCommand)
        {
            string strCommandTmp = strCommand.Trim();
            string[] arComList = null;
            //ArrayList arComList=new ArrayList();

            if (strCommandTmp.Trim().Length == 0)
                return;
            if (strCommandTmp.Substring(0, 1) != "/")
                return;

            arComList = strCommandTmp.Split('|');

            CommandProcess(arComList);
        }
        #endregion

        #region CommandProcess
        /// <summary>
        /// Command Processed
        /// </summary>
        /// <param name="strCommand"></param>
        private void CommandProcess(string[] strCommand)
        {
            string strCom = CommandFormat(strCommand[0]);

            switch (strCom)
            {
                case "/LISTALLDIRPATH":
                    ListAllDirectoryPaths(strCommand[1]);
                    break;
                case "/LISTDIRPATH":
                    ListTargetDirectoryPaths(strCommand[1], strCommand[2]);
                    break;
                case "/LISTFILES":
                    ListTargetFilesPath(strCommand[1], strCommand[2]);
                    break;
                case "/GETXMLFILE":
                    GetXMLFileContent(strCommand[1]);
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region CommandFormat
        /// <summary>
        /// Command Formated
        /// </summary>
        /// <param name="strCommand"></param>
        /// <returns></returns>
        private string CommandFormat(string strCommand)
        {
            string strCommandTmp = strCommand.ToUpper();

            return strCommandTmp;
        }
        #endregion

        #region ListAllDirectoryPaths
        /// <summary>
        /// List All Directory Paths
        /// </summary>
        /// <param name="strPath"></param>
        private void ListAllDirectoryPaths(string strPath)
        {
            string[] strPathTmp;
            //Init parameter
            //DirectoriesPathList = new ArrayList();

            strPathTmp = Directory.GetDirectories(strPath);
            for (int cnt = 0; cnt < strPathTmp.Length; cnt++)
            {
                //DirectoriesPathList.Add(strPathTmp[cnt]);
                strRespondContent += strPathTmp[cnt] + "/r/n";
            }
        }
        #endregion

        #region ListTargetDirectoryPaths
        /// <summary>
        /// List Target Directory's Paths
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="strSearchedDirectoryName"></param>
        private void ListTargetDirectoryPaths(string strPath, string strSearchedDirectoryName)
        {
            //Init parameter
            //DirectoriesPathList = new ArrayList();
            //Get Target Directory Path
            strTargetDirectoryPath = strPath;

            SearchDirectory(strPath, strSearchedDirectoryName);
        }
        #endregion

        #region ListTargetFilesPath
        /// <summary>
        /// List Target Files's Path
        /// </summary>
        /// <param name="strFileType"></param>
        /// <returns></returns>
        private void ListTargetFilesPath(string strDirectoryPath,string strFileType)
        {
            //if (DirectoriesPathList == null)
            //{
            //    strErrorMsg = "Please do LISTDIRPATH first.";
            //    return;
            //}

            //FilesPathList = new ArrayList();
            ArrayList arFilesPathTmp = new ArrayList();

            //try
            //{
            //    for (int cnt = 0; cnt < DirectoriesPathList.Count; cnt++)
            //    {
            //        arFilesPathTmp = GetFilesPath(DirectoriesPathList[cnt].ToString(), strFileType);
            //        if (arFilesPathTmp == null)
            //            continue;
            //        for (int cnt2 = 0; cnt2 < arFilesPathTmp.Count; cnt2++)
            //        {
            //            FilesPathList.Add(arFilesPathTmp[cnt2]);
            //            strRespondContent += arFilesPathTmp[cnt2] + "/r/n";
            //        }
            //    }
            //}
            //catch (System.IO.IOException e)
            //{
            //    throw e;
            //}

            try
            {               
                arFilesPathTmp = GetFilesPath(strDirectoryPath, strFileType);
                if (arFilesPathTmp == null)
                    return;
                for (int cnt2 = 0; cnt2 < arFilesPathTmp.Count; cnt2++)
                {
                    strRespondContent += arFilesPathTmp[cnt2] + "/r/n";
                }
            }
            catch (System.IO.IOException e)
            {
                throw e;
            }

        }
        #endregion

        #region GetXMLFileContent
        /// <summary>
        /// Get XML File's Content
        /// </summary>
        /// <param name="strXMLFilePath"></param>
        private void GetXMLFileContent(string strXMLFilePath)
        {
            ReadMSNXMLFile(strXMLFilePath);
        }
        #endregion

        #region MSN's XML file process
        #region ReadXMLFileFrom
        public void ReadMSNXMLFile(string strXMLFilePath)
        {
            XmlTextReader reader = new XmlTextReader(strXMLFilePath);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(reader);
            XmlNode xnod = xmlDoc.DocumentElement;
            XmlNamedNodeMap mapAttributes = xnod.Attributes;
            ReadMSNXMLFileFromNode(xnod, 1);

            reader.Close();
            xmlDoc.RemoveAll();
            reader = null;
            xmlDoc = null;
        }
        #endregion

        #region ReadMSNXMLFileFromNode
        private void ReadMSNXMLFileFromNode(XmlNode xnod, Int32 intLevel)
        {
            //intLevel depth control
            XmlNode xnodWorking;
            //Get attributes from node
            if (xnod.NodeType == XmlNodeType.Element)
            {
                XmlNamedNodeMap mapAttributes = xnod.Attributes;
                //get attributes and value
                foreach (XmlNode xnodAttribute in mapAttributes)
                {
                    if (xnodAttribute.Name == "FriendlyName")
                    {
                        if (blnAToBFlag == false)
                        {
                            blnAToBFlag = true;
                            strRespondContent += xnodAttribute.Value + "->";
                        }
                        else
                        {
                            blnAToBFlag = false;
                            strRespondContent += xnodAttribute.Value + "/r/n";
                        }
                    }
                    else if (xnodAttribute.Name == "Date")
                    {
                        strRespondContent += xnodAttribute.Value + "-";
                    }
                    else if (xnodAttribute.Name == "Time")
                    {
                        strRespondContent += xnodAttribute.Value + "/r/n";
                    }
                    else if (xnodAttribute.Name == "Style")
                    {
                        strRespondContent += xnod.InnerText + "/r/n";
                    }
                }
                //check Child Nodes
                if (xnod.HasChildNodes)
                {
                    xnodWorking = xnod.FirstChild;

                    while (xnodWorking != null)
                    {
                        ReadMSNXMLFileFromNode(xnodWorking, intLevel + 1);
                        xnodWorking = xnodWorking.NextSibling;
                    }
                }
            }
        }
        #endregion
        #endregion

        #region Disposeed
        /// <summary>
        /// Disposeed all
        /// </summary>
        public void Disposeed()
        {
            //if (DirectoriesPathList != null)
            //    DirectoriesPathList.Clear();
            //DirectoriesPathList = null;
        }
        #endregion

    }
}

發佈了6 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章