Ejemplo n.º 1
0
        /// <summary>
        /// 获取指定路径下的文件目录和文件信息
        /// </summary>
        /// <param name="path">指定路径</param>
        /// <returns>string</returns>
        public static string GetDirectoryInfo(string path)
        {
            var result = new StringBuilder();

            if (Directory.Exists(path))
            {
                var comparer = new IComparerHelper <string>((x, y) =>
                                                            x.IsValidDecimal() && y.IsValidDecimal()
                   ? decimal.Compare(x.ToDecimal(), y.ToDecimal())
                   : string.Compare(x, y));

                var di    = new DirectoryInfo(path);
                var files = di.GetFiles();
                var dirs  = di.GetDirectories();
                result.Append("{")
                .Append($"\"dirName\":\"{path.Substring("\\")}\",")
                .Append($"\"filesName\":{files?.Select(o => o.Name).OrderBy(o => o.Contains(".") ? o.Substring(0, o.LastIndexOf(".")) : o, comparer).ToJson()},")
                .Append($"\"childrensDirInfo\":{GetDirectoryInfo(dirs)}")
                .Append("}");
            }
            return(result.ToString());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="dir">目录实例数组</param>
        /// <returns>string</returns>
        public static string GetDirectoryInfo(DirectoryInfo[] dir)
        {
            var result = new StringBuilder();

            if (dir.IsNotNull())
            {
                var comparer = new IComparerHelper <string>((x, y) =>
                                                            x.IsValidDecimal() && y.IsValidDecimal()
                   ? decimal.Compare(x.ToDecimal(), y.ToDecimal())
                   : string.Compare(x, y));

                var query = (from a in dir
                             let files = a.GetFiles().Select(o => o.Name)
                                         let dirs = a.GetDirectories()
                                                    select new
                {
                    dirName = a.Name,
                    filesName = files,
                    dirsName = dirs
                })
                            .OrderBy(o => o.dirName)
                            .ToList();
                result.Append("[");
                query.ForEach(o =>
                {
                    result.Append("{")
                    .Append($"\"dirName\":\"{o.dirName}\",")
                    .Append($"\"filesName\":{o.filesName.OrderBy(s => s.Contains(".") ? s.Substring(0, s.LastIndexOf(".")) : s, comparer).ToJson()},")
                    .Append($"\"childrensDirInfo\":{GetDirectoryInfo(o.dirsName)}")
                    .Append("},");
                });
                result = query.Count > 0 ? result.Remove(result.Length - 1, 1) : result;
                result.Append("]");
            }
            return(result.ToString());
        }