SharePoint 压缩打包文件代码分享

  前言

  最近碰到这样一个需求,用户需要批量打包下载sharepoint文档库中的文档,所以,就需要开发一个打包下载的服务。

  然后,把打包的代码分享给大家,也许会有需要的人。

        static void Main(string[] args)
        {
            string filesPath = "/DC/T1.txt;/DC/T2.txt";
            CreateZipFile(filesPath, @"C:Temp", "http://localhost");
        }

        /// <summary>
        /// 创建压缩包
        /// </summary>
        /// <param name="filesPath"></param>
        /// <param name="zipFilePath"></param>
        private static void CreateZipFile(string filesPath, string zipFilePath, string siteUrl)
        {
            string[] filenames = filesPath.Split(';');
            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    string tempName = Guid.NewGuid().ToString().Replace("-", "") + ".zip";
                    zipFilePath = zipFilePath + tempName;
                    Stream sr = File.Create(zipFilePath);
                    using (ZipOutputStream s = new ZipOutputStream(sr))
                    {
                        s.SetLevel(9);// 压缩级别 0-9
                        byte[] buffer = null;
                        foreach (string file in filenames)
                        {
                            ZipEntry entry = new ZipEntry(GetFileName(file));
                            entry.DateTime = DateTime.Now;
                            s.PutNextEntry(entry);
                            string filename = web.Url + file;
                            SPFile ff = web.GetFile(filename);
                            buffer = ff.OpenBinary();
                            int sourceBytes = buffer.Length;
                            s.Write(buffer, 0, sourceBytes);
                        }
                        s.Finish();
                        s.Close();
                        sr.Close();
                        FileStream fs = File.Open(zipFilePath, FileMode.OpenOrCreate);
                        web.Lists["Temp"].RootFolder.Files.Add(web.ServerRelativeUrl + web.Lists["Temp"].RootFolder.Url + "/" + tempName, fs, true);
                        fs.Close();
                        File.Delete(zipFilePath);
                    }
                }
            }
            return;
        }

        public static string GetFileName(string filePath)
        {
            string fileName = filePath.Substring(filePath.LastIndexOf('/') + 1, filePath.Length - filePath.LastIndexOf('/') - 1);
            return fileName;
        }
原文地址:https://www.cnblogs.com/jianyus/p/8931969.html