Ejemplo n.º 1
0
        /// <summary>
        /// 下载一个远程文件到指定的文件路径里
        /// </summary>
        /// <param name="davFile">一个WebDavFile的实体</param>
        /// <param name="localFile">本地的文件地址</param>
        /// <returns></returns>
        private DownloadInfo DownloadFile(WebDavFile davFile, string localFile)
        {
            DownloadInfo info = new DownloadInfo {
                FileUrl = davFile.Url
            };

            try
            {
                DownloadManager manager    = new DownloadManager(GetCredentials());
                string          remoteFile = davFile.Url;
                bool            result     = false;
                if (File.Exists(localFile))
                {
                    FileInfo fm = new FileInfo(localFile);
                    //判断本地文件是否和远程的一样
                    if (davFile.LastModifyDate == fm.LastWriteTime && davFile.Length == fm.Length)
                    {
                        info.Success = true;
                        result       = true;
                    }
                }
                if (!info.Success)
                {
                    string folder = localFile.Substring(0, localFile.LastIndexOf("\\") + 1);

                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    FileInfo file = new FileInfo(localFile);

                    if (file.Directory != null)
                    {
                        Directory.CreateDirectory(file.Directory.FullName);
                    }
                    //下载文件到指定的地址
                    result = manager.DownloadFile(davFile, localFile);

                    //更改文件最后修改时间
                    if (davFile.LastModifyDate != null)
                    {
                        File.SetLastWriteTime(localFile, davFile.LastModifyDate.Value);
                    }

                    info.Success = true;
                }
            }
            catch (Exception ex)
            {
                info.Success = false;
                info.Message = ex.Message;
            }
            return(info);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 下载一个远程文件到指定的文件夹里,会根据远程文件的地址创建对应的目录结构
        /// </summary>
        /// <param name="file"></param>
        /// <param name="defaultFoder"></param>
        /// <param name="index">当前下载第几个</param>
        /// <param name="total">总共文件数</param>
        /// <returns></returns>
        private DownloadInfo Download(WebDavFile file, string defaultFoder, int index = 1, int total = 1)
        {
            string folderPath = CreateFolder(file.Url, defaultFoder);
            string localFile  = folderPath + "\\" + file.DispalyName;

            file.DownloadPath       = localFile;
            file.DownloadFolderPath = folderPath;
            //如若DownloadCompling不为空,执行相关的事件
            DownloadCompling?.Invoke(file, index, total);
            //下载文件到本地
            DownloadInfo result = DownloadFile(file, localFile);

            // //DownloadCompleted,执行相关的事件
            DownloadCompleted?.Invoke(file, index, total);

            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 下载文件到本地指定的路径
        /// </summary>
        /// <param name="file">WebDav实体</param>
        /// <param name="localfile">本地文件路径</param>
        /// <returns></returns>
        public bool DownloadFile(WebDavFile file, string localfile)
        {
            bool isDownloadSuccessfully = false;

            try
            {
                if (this.WebClientDownloadInstallerFile(file, localfile))
                {
                    isDownloadSuccessfully = true;
                }
            }
            catch
            {
                isDownloadSuccessfully = false;
            }

            return(isDownloadSuccessfully);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="file">Webdav文件实例</param>
        /// <param name="localfile">下载文件地址</param>
        /// <returns>True:下载成功;false:下载不成功;</returns>
        private bool WebClientDownloadInstallerFile(WebDavFile file, string localfile)
        {
            string url = file.Url;

            bool            resumeDownload         = IsResume(url, localfile);
            string          tempFileName           = localfile + ".temp";
            bool            isDownloadSuccessfully = false;
            FileMode        fm         = FileMode.Create;
            Stream          stream     = null;
            FileStream      fileStream = null;
            HttpWebResponse response   = null;

            try
            {
                Uri            installerUrl   = new Uri(url);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Credentials = _credentials;

                if (resumeDownload)
                {
                    //断点续传
                    FileInfo fn = new FileInfo(tempFileName);
                    httpWebRequest.Headers["Range"] = (new RangeHeaderValue(fn.Length, file.Length)).ToString();
                    fm = FileMode.Append;
                }

                response = (HttpWebResponse)httpWebRequest.GetResponseAsync().GetAwaiter().GetResult();
                stream   = response.GetResponseStream();

                //获取响应流,写入到文件
                double contentLength    = DownloadManager.GetContentLength(response);
                byte[] buffer           = new byte[BufferSize];
                long   downloadedLength = 0;
                int    currentDataLength;
                fileStream = new FileStream(tempFileName, fm);

                while ((currentDataLength = stream.Read(buffer, 0, BufferSize)) > 0)
                {
                    fileStream.Write(buffer, 0, currentDataLength);
                    downloadedLength += (long)currentDataLength;
                }

                if (currentDataLength >= 0)
                {
                    isDownloadSuccessfully = true;
                }
            }
            catch (Exception ex)
            {
                // todo
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Flush();
                    fileStream.Dispose();
                }
                if (stream != null)
                {
                    stream.Dispose();
                }

                if (response != null)
                {
                    response.Dispose();
                }
            }
            if (isDownloadSuccessfully)
            {
                if (File.Exists(localfile))
                {
                    Util.DeleteFileIfExists(localfile);
                }
                File.Move(tempFileName, localfile);

                string tempFileInfoName = localfile + ".temp.info";
                if (File.Exists(tempFileInfoName))
                {
                    Util.DeleteFileIfExists(tempFileInfoName);
                }
            }
            return(isDownloadSuccessfully);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///  获取WebDav远程地址的文件列表地址
        /// </summary>
        /// <param name="remoteFilePth">远程文件目录,如http://172.23.0.1/met<</param>
        /// <param name="filters">后缀名过滤</param>
        /// <returns>返回的所有的文件集合</returns>
        public List <WebDavFile> GetFiles(string remoteFilePth, params string[] filters)
        {
            List <WebDavFile> filesList = new List <WebDavFile>();
            Uri listUri = GetServerUrl(remoteFilePth, true);

            if (remoteFilePth.ToLower().StartsWith("http://") || remoteFilePth.StartsWith("https://"))
            {
                listUri = new Uri(remoteFilePth);
            }
            StringBuilder propfind = new StringBuilder();

            propfind.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            propfind.Append("<propfind xmlns=\"DAV:\">");
            propfind.Append("  <allprop/>");
            propfind.Append("</propfind>");

            IDictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Depth", "1");
            using (
                HttpWebResponse response = HttpRequest(listUri, "PROPFIND", headers,
                                                       Encoding.UTF8.GetBytes(propfind.ToString())))
            {
                using (Stream stream = response.GetResponseStream())
                {
                    System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
                    xml.Load(stream);
                    XmlNamespaceManager xmlNsManager = new XmlNamespaceManager(xml.NameTable);
                    xmlNsManager.AddNamespace("d", "DAV:");
                    Windows.Data.Xml.Dom.XmlDocument xmlDom = new Windows.Data.Xml.Dom.XmlDocument();
                    xmlDom.LoadXml(xml.OuterXml);
                    Windows.Data.Xml.Dom.XmlNodeList listNodes = xmlDom.DocumentElement.ChildNodes;

                    for (int i = 0; i < listNodes.Count; i++)
                    {
                        IXmlNode node = listNodes[i];

                        IXmlNode first = node.ChildNodes.Where(x => x.NodeName.ToLower() == "d:href").FirstOrDefault();

                        if (first.InnerText == remoteFilePth)
                        {
                            continue;
                        }

                        WebDavFile oWebDavFile = new WebDavFile {
                            Url = first.InnerText
                        };
                        IXmlNode secNode = node.ChildNodes.Where(x => x.NodeName.ToLower() == "d:propstat").FirstOrDefault();

                        IXmlNode propsNode = secNode.ChildNodes.Where(x => x.NodeName.ToLower() == "d:prop").FirstOrDefault();
                        //文件的显示名
                        IXmlNode attrNode = propsNode.ChildNodes.Where(x => x.NodeName.ToLower() == "d:displayname")
                                            .FirstOrDefault();

                        oWebDavFile.DispalyName = attrNode.InnerText;

                        if (oWebDavFile.DispalyName == remoteFilePth)
                        {
                            continue;
                        }
                        //文件的内容类型
                        attrNode = propsNode.ChildNodes.Where(x => x.NodeName.ToLower() == "d:getcontenttype")
                                   .FirstOrDefault();

                        oWebDavFile.ContentType = attrNode.InnerText;

                        //文件的最后修改时间
                        attrNode = propsNode.ChildNodes.Where(x => x.NodeName.ToLower() == "d:getlastmodified")
                                   .FirstOrDefault();

                        oWebDavFile.LastModifyDate = DateTime.Parse(attrNode.InnerText);

                        //文件的创建时间
                        attrNode = propsNode.ChildNodes.Where(x => x.NodeName.ToLower() == "d:creationdate")
                                   .FirstOrDefault();

                        oWebDavFile.CreateDate = DateTime.Parse(attrNode.InnerText);

                        //文件的大小
                        attrNode = propsNode.ChildNodes.Where(x => x.NodeName.ToLower() == "d:getcontentlength")
                                   .FirstOrDefault();

                        oWebDavFile.Length = long.Parse(attrNode.InnerText);

                        filesList.Add(oWebDavFile);
                    }
                }
            }

            List <WebDavFile> folderDavFiles = filesList.Where(x => x.Length == 0 && x.Url.EndsWith("/")).ToList();

            foreach (WebDavFile file in folderDavFiles)
            {
                if (file.Length == 0 && file.Url.EndsWith("/"))
                {
                    filesList.AddRange(GetFiles(file.Url));
                }
            }

            var q = filesList.Where(x => x.Length != 0);

            if (filters != null)
            {
                q = filters.Aggregate(q, (current, filter) => current.Where(x => !x.Url.ToLower().EndsWith(filter.ToLower())));
            }

            return(q.ToList());
        }