当前位置: 代码迷 >> C# >> 见见这个C#压缩文件代码有没有错!
  详细解决方案

见见这个C#压缩文件代码有没有错!

热度:104   发布时间:2016-05-05 04:26:39.0
看看这个C#压缩文件代码有没有错!!
引用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Packaging;
namespace PolicyUpload.Util
{
    class testGzip
    {
        public string SourceFolderPath{get;set;}




        public testGzip(string sourceFolderPath)
        {
            SourceFolderPath = sourceFolderPath;
        }


        public void ZipFolder(string zipFilePath)
        {
            using (Package package = Package.Open(zipFilePath, FileMode.Create))
            {
                DirectoryInfo di = new DirectoryInfo(SourceFolderPath);
                ZipDirectory(di,package);
            }

        }

        private void ZipDirectory(DirectoryInfo di, Package package)
        {
            foreach (FileInfo fi in di.GetFiles())
            {
                string relativePath = fi.FullName.Replace(SourceFolderPath, String.Empty);
                relativePath = relativePath.Replace("\\","/");
                PackagePart part = package.CreatePart(new Uri(relativePath,UriKind.Relative),System.Net.Mime.MediaTypeNames.Application.Zip);
                using (FileStream fs = fi.OpenRead())
                {
                    CopyStream(fs, part.GetStream());
                }
            }
            foreach (DirectoryInfo subDi in di.GetDirectories())
            {
                ZipDirectory(di, package);
            }
        }
        private void CopyStream(Stream scource,Stream target)
        {
            const int bufSize = 0x1000;
            byte[] buf = new byte[bufSize];
            int byteRead = 0;
            while ((byteRead = scource.Read(buf,0,bufSize)) > 0 )
            {
                target.Write(buf, 0, byteRead);
            }
        }
    }
}


网上参考的...运行后   " 正由另一进程使用,因此该进程无法访问此文件" 的错误!
------解决思路----------------------
“网上”告诉你怎样使用vs调试器来中断在异常语句上,并贴出调试画面了吧?