Exemple #1
0
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="path">文件链接(物理路径)</param>
        /// <param name="realName">要显示下载时的文件名</param>
        public static void DownLoadFile(string path, string realName)
        {
            path     = ComFile.MapPath(path);
            realName = string.IsNullOrEmpty(realName) ? "文件下载" : realName;
            FileInfo     info     = new FileInfo(path);
            HttpResponse Response = HttpContext.Current.Response;

            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer      = false;
            Response.ContentType = "application/octet-stream";
            string exp = HttpContext.Current.Request.UserAgent.ToLower();

            if (exp.IndexOf("msie") > -1)
            {
                //当客户端使用IE时,对其进行编码;We should encode the filename when our visitors use IE
                //使用 ToHexString 代替传统的 UrlEncode();We use "ToHexString" replaced "context.Server.UrlEncode(fileName)"
                realName = XCLNetTools.Encode.Hex.ToHexString(realName);
            }
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + realName.Replace("+", "_").Replace(" ", ""));
            Response.AppendHeader("Content-Length", info.Length.ToString());
            Response.WriteFile(path);
            Response.Flush();
            Response.End();
        }
Exemple #2
0
 /// <summary>
 /// 复制文件,若目标目录不存在,则自动创建
 /// </summary>
 public static bool CopyFile(string srcPath, string dstPath, bool overwrite = true)
 {
     lock (copy_lock)
     {
         XCLNetTools.FileHandler.FileDirectory.MakeDirectory(GetFileFolderPath(dstPath));
         File.Copy(ComFile.MapPath(srcPath), ComFile.MapPath(dstPath), overwrite);
         return(File.Exists(ComFile.MapPath(dstPath)));
     }
 }
Exemple #3
0
 /// <summary>
 /// 获取路径所在的文件夹名称,如:c:\a\b\ --> b;  c:\a\b\c.pdf --> b
 /// </summary>
 public static string GetPathFolderName(string path, bool isFolderPath)
 {
     if (string.IsNullOrWhiteSpace(path))
     {
         return(string.Empty);
     }
     path = ComFile.GetStandardPath(path, isFolderPath);
     return(Path.GetFileName(Path.GetDirectoryName(path)));
 }
Exemple #4
0
        /// <summary>
        /// 根据指定文件的物理路径Path,将它转换为相对于RootPath的Url相对路径
        /// 例如:
        /// GetUrlRelativePath("C:\Program Files\Information\","C:\Program Files\Information\A\B\C.txt")=>"A/B/C.txt"
        /// GetUrlRelativePath("C:\Program Files\Information\","C:\A\B\C.txt")=>"../../A/B/C.txt"
        /// </summary>
        /// <param name="rootPath">根物理路径</param>
        /// <param name="path">指定要转换的物理路径</param>
        /// <returns>path相对于rootPath的url路径</returns>
        public static string GetUrlRelativePath(string rootPath, string path)
        {
            if (string.IsNullOrEmpty(rootPath) || string.IsNullOrEmpty(path))
            {
                return(string.Empty);
            }
            Uri root = new Uri(ComFile.MapPath(rootPath));
            Uri p    = new Uri(ComFile.MapPath(path));

            return(root.MakeRelativeUri(p).ToString());
        }
Exemple #5
0
        /// <summary>
        /// 返回文件大小(字节)
        /// </summary>
        /// <returns>文件大小 byte</returns>
        public static long GetFileSize(string filePath)
        {
            long s = 0;

            if (System.IO.File.Exists(ComFile.MapPath(filePath)))
            {
                FileInfo fi = new FileInfo(ComFile.MapPath(filePath));
                s = fi.Length;
            }
            return(s);
        }
Exemple #6
0
 /// <summary>
 /// 取得文件夹中的子文件夹列表
 /// </summary>
 /// <param name="path">文件夹路径</param>
 /// <returns>字符串数组(存储了一个或多个文件夹名)</returns>
 public static string[] GetFolders(string path)
 {
     try
     {
         return(System.IO.Directory.GetDirectories(ComFile.MapPath(path)));
     }
     catch
     {
         return(new string[] { });
     }
 }
Exemple #7
0
 /// <summary>
 /// 使用新的文件夹名,更新指定路径path中的文件夹名。如:("C:\demo\a\","b")=>C:\demo\b\  ;  ("C:\demo\a\b.pdf","c")=>C:\demo\c\b.pdf
 /// </summary>
 public static string ChangePathByFolderName(string path, string name, bool isFolderPath)
 {
     if (string.IsNullOrWhiteSpace(path))
     {
         return(string.Empty);
     }
     if (isFolderPath)
     {
         path = ComFile.GetStandardPath(path, true);
         return(ComFile.GetStandardPath(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), name), true));
     }
     return(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), name, Path.GetFileName(path)));
 }
Exemple #8
0
 /// <summary>
 /// 取得文件夹中的文件列表
 /// </summary>
 /// <param name="path">文件夹路径</param>
 /// <param name="isContainsHiddenFile">是否包含隐藏文件,默认为:true</param>
 /// <returns>字符串数组(存储了一个或多个文件名)</returns>
 public static string[] GetFolderFiles(string path, bool isContainsHiddenFile = true)
 {
     path = ComFile.MapPath(path);
     try
     {
         var arr = System.IO.Directory.GetFiles(path);
         if (arr.Length > 0 && !isContainsHiddenFile)
         {
             arr = arr.AsParallel().Where(k => !ComFile.IsHiddenFile(k)).ToArray();
         }
         return(arr);
     }
     catch
     {
         return(new string[] { });
     }
 }
Exemple #9
0
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>若为true,则删除成功</returns>
        public static bool DeleteFile(string filePath)
        {
            bool isSuccess = false;

            filePath = ComFile.MapPath(filePath);
            if (System.IO.File.Exists(filePath))
            {
                try
                {
                    System.IO.File.Delete(filePath);
                    isSuccess = !System.IO.File.Exists(filePath);
                }
                catch
                {
                }
            }
            else
            {
                isSuccess = true;
            }
            return(isSuccess);
        }
Exemple #10
0
        /// <summary>
        /// 获取指定目录下的所有文件及文件夹信息
        /// </summary>
        /// <param name="dirPath">要获取信息的目录路径</param>
        /// <param name="rootPath">根路径(设置该值后,返回的信息实体中将包含相对于该根路径的相对路径信息)</param>
        /// <param name="webRootPath">web根路径(用于生成该文件或文件夹的web路径),如:http://www.a.com/web/</param>
        /// <returns>文件信息list</returns>
        public static List <XCLNetTools.Entity.FileInfoEntity> GetFileList(string dirPath, string rootPath = "", string webRootPath = "")
        {
            if (!string.IsNullOrEmpty(dirPath))
            {
                dirPath = XCLNetTools.FileHandler.ComFile.MapPath(dirPath);
            }
            if (!string.IsNullOrEmpty(rootPath))
            {
                rootPath = XCLNetTools.FileHandler.ComFile.MapPath(rootPath);
            }

            if (string.IsNullOrEmpty(dirPath) || FileDirectory.IsEmpty(dirPath))
            {
                return(null);
            }
            int idx = 1;

            List <XCLNetTools.Entity.FileInfoEntity> result = new List <Entity.FileInfoEntity>();

            XCLNetTools.Entity.FileInfoEntity tempFileInfoEntity = null;
            //文件夹
            var directories = System.IO.Directory.EnumerateDirectories(dirPath);

            if (null != directories && directories.Any())
            {
                directories.ToList().ForEach(k =>
                {
                    var dir = new System.IO.DirectoryInfo(k);
                    if (dir.Exists)
                    {
                        tempFileInfoEntity              = new Entity.FileInfoEntity();
                        tempFileInfoEntity.ID           = idx++;
                        tempFileInfoEntity.Name         = dir.Name;
                        tempFileInfoEntity.IsFolder     = true;
                        tempFileInfoEntity.Path         = k;
                        tempFileInfoEntity.RootPath     = rootPath;
                        tempFileInfoEntity.RelativePath = ComFile.GetUrlRelativePath(rootPath, k);
                        tempFileInfoEntity.WebPath      = webRootPath.TrimEnd('/') + "/" + tempFileInfoEntity.RelativePath;
                        tempFileInfoEntity.ModifyTime   = dir.LastWriteTime;
                        tempFileInfoEntity.CreateTime   = dir.CreationTime;
                        result.Add(tempFileInfoEntity);
                    }
                });
            }

            //文件
            string[] files = XCLNetTools.FileHandler.ComFile.GetFolderFiles(dirPath);
            if (null != files && files.Length > 0)
            {
                files.ToList().ForEach(k =>
                {
                    var file = new System.IO.FileInfo(k);
                    if (file.Exists)
                    {
                        tempFileInfoEntity              = new Entity.FileInfoEntity();
                        tempFileInfoEntity.ID           = idx++;
                        tempFileInfoEntity.Name         = file.Name;
                        tempFileInfoEntity.IsFolder     = false;
                        tempFileInfoEntity.Path         = k;
                        tempFileInfoEntity.RootPath     = rootPath;
                        tempFileInfoEntity.RelativePath = ComFile.GetUrlRelativePath(rootPath, k);
                        tempFileInfoEntity.WebPath      = webRootPath.TrimEnd('/') + "/" + tempFileInfoEntity.RelativePath;
                        tempFileInfoEntity.ModifyTime   = file.LastWriteTime;
                        tempFileInfoEntity.CreateTime   = file.CreationTime;
                        tempFileInfoEntity.Size         = file.Length;
                        tempFileInfoEntity.ExtName      = (file.Extension ?? "").Trim('.');
                        result.Add(tempFileInfoEntity);
                    }
                });
            }

            return(result);
        }
Exemple #11
0
 /// <summary>
 /// 取得文件夹中的文件列表
 /// </summary>
 /// <param name="path">文件夹路径</param>
 /// <returns>字符串数组(存储了一个或多个文件名)</returns>
 public static string[] GetFolderFiles(string path)
 {
     return(System.IO.Directory.GetFiles(ComFile.MapPath(path)));
 }
Exemple #12
0
        /// <summary>
        /// 根据浏览器书签文件地址,返回list
        /// </summary>
        /// <param name="path">书签文件地址</param>
        /// <returns>书签list</returns>
        public static List <XCLNetTools.Entity.BookmarkEntity> GetBookmark(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }
            path = ComFile.MapPath(path.Trim());
            Regex  reg     = new Regex(@"(<dt>)|(<p>)|(\n)|(\r)", RegexOptions.IgnoreCase);
            string strFile = System.IO.File.ReadAllText(path, System.Text.Encoding.UTF8);

            strFile = reg.Replace(strFile, "");
            strFile = new Regex(@">\s+<").Replace(strFile, "><");

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(strFile);

            int idx = 0;

            XCLNetTools.Entity.BookmarkEntity        model = null;
            List <XCLNetTools.Entity.BookmarkEntity> lst   = new List <XCLNetTools.Entity.BookmarkEntity>();

            Action <HtmlAgilityPack.HtmlNode, int> GetNodeItems = null;

            GetNodeItems = (HtmlAgilityPack.HtmlNode rootNode, int parentId) =>
            {
                //收藏夹
                HtmlAgilityPack.HtmlNodeCollection folderNodeList = rootNode.SelectNodes("h3");
                if (null != folderNodeList && folderNodeList.Count > 0)
                {
                    foreach (var m in folderNodeList)
                    {
                        model          = new XCLNetTools.Entity.BookmarkEntity();
                        model.IsFolder = true;
                        model.Id       = (++idx);
                        model.ParentId = parentId;
                        model.Name     = m.InnerText;
                        lst.Add(model);
                        //m的子项
                        var nextNode = m.NextSibling;
                        if (null != nextNode && string.Equals(nextNode.Name, "dl", StringComparison.CurrentCultureIgnoreCase))
                        {
                            GetNodeItems(nextNode, model.Id);
                        }
                    }
                }

                //收藏项
                HtmlAgilityPack.HtmlNodeCollection nodeList = rootNode.SelectNodes("a");
                if (null != nodeList && nodeList.Count > 0)
                {
                    foreach (var m in nodeList)
                    {
                        model          = new XCLNetTools.Entity.BookmarkEntity();
                        model.Id       = (++idx);
                        model.IcoURL   = null == m.Attributes["ICON"] ? "" : m.Attributes["ICON"].Value;
                        model.IsFolder = false;
                        model.ParentId = parentId;
                        model.Name     = m.InnerText;
                        model.Url      = null == m.Attributes["HREF"] ? "" : m.Attributes["HREF"].Value;
                        lst.Add(model);
                    }
                }
            };

            GetNodeItems(doc.DocumentNode.ChildNodes["dl"], idx);

            return(lst);
        }
Exemple #13
0
 /// <summary>
 /// 复制整个文件夹的内容并将此文件夹作为目标文件夹的一个子文件夹
 /// </summary>
 /// <param name="sourceDirName">原路径</param>
 /// <param name="destDirName">目标路径</param>
 /// <param name="copySubDirs">是否复制子目录</param>
 public static void CopyDirAsSub(string sourceDirName, string destDirName, bool copySubDirs)
 {
     destDirName = Path.Combine(destDirName, GetPathFolderName(sourceDirName, true));
     ComFile.CopyDir(sourceDirName, destDirName, copySubDirs);
 }
        /// <summary>
        /// 将所有路径转换成唯一的路径,如果有同名路径,则在后面自动标号(如:a.txt => a(1).txt、d:\a\ => d:\a(1)\)
        /// 1、返回的列表与源列表的顺序是一样的
        /// 2、传入的路径必须是标准的路径,并且这些路径可能同时包含文件路径与文件夹路径
        /// </summary>
        public static List <string> ConvertPathToUniqueList(List <string> standardPathList)
        {
            if (standardPathList.IsNullOrEmpty())
            {
                return(new List <string>());
            }
            var hs    = new HashSet <string>();
            var tpLst = new List <Tuple <string, string> >();
            var reg   = new Regex(@"\((?<idx>\d+)\)$");

            standardPathList.ForEach(p =>
            {
                if (string.IsNullOrWhiteSpace(p))
                {
                    tpLst.Add(new Tuple <string, string>(p, p));
                    return;
                }

                var isFolder = ComFile.IsFolderPathByCharFlag(p);
                var tempPath = p;

                //无限循环计算唯一的路径
                while (true)
                {
                    var key = tempPath.ToUpper().TrimEnd('\\');

                    //如果当前路径在当前时刻未重复,则直接返回结果
                    if (!hs.Contains(key))
                    {
                        hs.Add(key);
                        break;
                    }

                    //如果当前不唯一,则更新名称后再判断是否唯一
                    if (isFolder)
                    {
                        var name    = ComFile.GetPathFolderName(tempPath, true);
                        var newName = string.Empty;
                        var mt      = reg.Match(name);
                        if (mt.Success && mt?.Groups?.Count > 0)
                        {
                            newName = reg.Replace(name, $"({Convert.ToInt32(mt.Groups["idx"].Value) + 1})");
                        }
                        else
                        {
                            newName = $"{name}(1)";
                        }
                        tempPath = ComFile.ChangePathByFolderName(tempPath, newName, true);
                    }
                    else
                    {
                        var name    = ComFile.GetFileName(tempPath, false);
                        var ext     = ComFile.GetExtName(tempPath);
                        var newName = string.Empty;
                        var mt      = reg.Match(name);
                        if (mt.Success && mt?.Groups?.Count > 0)
                        {
                            newName = reg.Replace(name, $"({Convert.ToInt32(mt.Groups["idx"].Value) + 1})");
                        }
                        else
                        {
                            newName = $"{name}(1)";
                        }
                        tempPath = ComFile.ChangePathByFileName(tempPath, ComFile.AppendExtToPath(newName, ext));
                    }
                }

                tpLst.Add(new Tuple <string, string>(p, tempPath));
            });

            return(tpLst.Select(k => k.Item2).ToList());
        }