Hiển thị các bài đăng có nhãn Parser folder and files. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Parser folder and files. Hiển thị tất cả bài đăng

Thứ Năm, 11 tháng 6, 2015

[PARSER] Parse folder and files to treeview structure on text file

Input: Directory Path
Output: Return string treeview structure

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

namespace ParserUtils
{
    /// 
    /// Class FileFolderToText.
    /// Parser folder and file structure to text file.
    /// 
    public class FileFolderToText
    {
        Dictionary<string, int> dictCounterType = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
        {
            {"Others", 0}
        };
        private string _otherExtension = string.Empty;
        private int _totalFile = 0;
        private int _totalFolder = 0;
        Dictionary<string, string> dicMapFileType = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
        {
            {".doc", "Word"},
            {".docx", "Word"},
            {".xls", "Excel File"},
            {".xlsx", "Excel File"},
            {".xml", "Xml File"},
            {".xsd", "Xsd File"},
            {".ppt", "Power Point File"},
            {".pptx", "Power Point File"},
            {".mdb", "Access File"},
            {".mpp", "Microsoft Project File"},
            {".pdf", "Pdf File"},
            {".png", "Image File"},
            {".gif", "Image File"},
            {".jpg", "Image File"},
            {".jpeg", "ImageFile"},
            {".bmp", "Image File"},
            {".txt", "Text File"},
            {".zip", "Zip File"},
            {".rar", "Rar File"},
            {".7z", "7Z File"},
            {".mht", "Html Document"},
            {".html", "Html File"},
            {".htm", "Html File"},
            {".exe", "Execute File"},
            {".ssc", "DScript File"},
            {".ini", "INI File"},
            {".inf", "INF File"},
            {".bat", "BAT File"},
            {".scc", "Source Control File"},
            {".vsd", "Visio File"},
            {".csv", "CSV File"},
            {".cs", "CSharp File"},
            {".vb", "VB File"},
            {".java", "Java File"},
            {".jsp", "JSP File"},
            {".diff", "Diffrent File"},
            {".resx", "Resource File"},
            {".json", "JSON File"},
            {".rtf", "RTF File"},
            {".rb", "Rubby File"},
            {".mp3", "MP3 File"},
            {".mp4", "MP4 File"},
            {".ico", "Icon File"}
        };

        private string _folderPath = string.Empty;
        public FileFolderToText(string folderPath)
        {
            _folderPath = folderPath;
        }
        public bool Save(string filePath, string data = null)
        {
            if (data == null)
                data = ToText(_folderPath);
            try
            {
                using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.GetEncoding(932)))
                {
                    sw.WriteLine("=======================");
                    sw.WriteLine(string.Format("Folder Path: {0}", _folderPath));
                    sw.WriteLine(string.Format("Total: {0} folder and {1} files.", _totalFolder, _totalFile));
                    sw.WriteLine("========Summary=========");
                    sw.WriteLine(_otherExtension);
                    foreach (var dict in dictCounterType)
                    {
                        sw.WriteLine(string.Format("Total: {0} {1} files.", dict.Value, dict.Key));
                    }
                    sw.WriteLine("=======================");
                    sw.Write(data);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// 
        /// Parse folder and files to the text.
        /// 
        /// "folderPath">The folder path.
        /// "indent">The space indent.
        /// System.String text tree structure.
        private string ToText(string folderPath, int indent = 0)
        {
            StringBuilder sb = new StringBuilder();
            DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
            if (dirInfo != null)
            {
                _totalFolder++;
                sb.Append(string.Empty.PadLeft(indent));
                sb.AppendLine(dirInfo.Name);
                DirectoryInfo[] lstDirInfo = dirInfo.GetDirectories();
                if (lstDirInfo.Length > 0)
                {
                    for (int i = 0; i < lstDirInfo.Length; i++)
                    {
                        sb.Append(ToText(lstDirInfo[i].FullName, indent + 4));
                    }
                }
                FileInfo[] lstFileInfo = dirInfo.GetFiles();
                if (lstFileInfo.Length > 0)
                {
                    for (int i = 0; i < lstFileInfo.Length; i++)
                    {
                        MappingFileType(Path.GetExtension(lstFileInfo[i].Name));
                        _totalFile++;
                        sb.Append(string.Empty.PadLeft(indent + 4));
                        sb.AppendLine(lstFileInfo[i].Name);
                    }
                }
            }
            return sb.ToString();
        }
        private void MappingFileType(string ext)
        {
            if (dicMapFileType.ContainsKey(ext))
            {
                if (dictCounterType.ContainsKey(dicMapFileType[ext]))
                    dictCounterType[dicMapFileType[ext]]++;
                else
                    dictCounterType[dicMapFileType[ext]] = 1;
            }
            else
            {
                dictCounterType["Others"]++;
                if (_otherExtension.Length == 0)
                {
                    _otherExtension += ext;
                }
                else if (_otherExtension.IndexOf(ext) == -1)
                {
                    _otherExtension += "|" + ext;
                }
            }
        }
    }
}

Execute:

FileFolderToText parseStructure = new FileFolderToText(@"D:\Develop");

parseStructure.Save(@"C:\OutputFile.txt");