码迷,mamicode.com
首页 > Windows程序 > 详细

C# 压缩 解压 复制文件夹

时间:2016-07-04 11:27:48      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

命名空间:namespace System.IO.Compression

 

压缩:

技术分享
//目标文件夹
            string fileDirPath = "/Downloads/试题" + userId + "_" + courseId;
            string downPath = Server.MapPath(fileDirPath);
            if (!Directory.Exists(downPath))
            {
                Directory.CreateDirectory(downPath);
            }
            System.IO.File.SetAttributes(downPath, FileAttributes.Normal);

//压缩文件
            string filePathZIP = Server.MapPath(fileDirPath) + ".zip";  //压缩文件夹
            if (System.IO.File.Exists(filePathZIP))
            {
                System.IO.File.Delete(filePathZIP);
            }
            System.IO.File.SetAttributes(downPath, FileAttributes.Normal);
            ZipFile.CreateFromDirectory(downPath, filePathZIP, CompressionLevel.Optimal, true);//压缩文件
            if (System.IO.Directory.Exists(downPath))
            {
                System.IO.Directory.Delete(downPath, true);    //删除原文件夹
            }
            return File(filePathZIP, "application/octet-stream", "试题" + "_" + userId + "_" + courseId + ".zip");
View Code

 

解压:

 

技术分享
                HttpPostedFileBase fileBase = Request.Files["fileImport"];
                string fileName = Path.GetFileName(fileBase.FileName);
                string fileNameNoExt = Path.GetFileNameWithoutExtension(fileBase.FileName);
                string extension = Path.GetExtension(fileName);
                if (extension.ToLower() != ".zip") //extension.ToLower() != ".xls" || extension.ToLower() != ".xlsx" || 
                {
                    //window.location.href=‘@Url.Action(‘CoursePackManage‘,‘ManageCourse‘)‘  window.location.href=‘/admin/ManageCourse/CoursePackManage‘;
                    return Content("<script type=‘text/javascript‘>alert(‘请上传zip格式的压缩文件‘);window.location.href=‘/admin/ManageCourse/CoursePackManage‘;</script>");
                }

                string filePath = "/UploadFile/试题/"; // +DateTime.Now.ToString("yyyyMMdd") + "/";

                if (!Directory.Exists(Server.MapPath(filePath))) //文件夹
                {
                    Directory.CreateDirectory(Server.MapPath(filePath));
                }
                string nowTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                string fullFileName = Server.MapPath(filePath + nowTime + "_" + userId + "_" + courseId + "_" + fileName);//文件名
                fileBase.SaveAs(fullFileName);

#region 压缩包

            if (extension.ToLower() == ".zip")
            {
                string destFilePath = Server.MapPath(filePath + nowTime + "_" + userId + "_" + courseId + "_" + fileNameNoExt); //不带后缀文件名字
                if (!Directory.Exists(destFilePath)) //文件夹
                {
                    Directory.CreateDirectory(destFilePath);
                }
                ZipFile.ExtractToDirectory(fullFileName, destFilePath, Encoding.Default); //解压文件

                System.IO.File.Delete(fullFileName);//解压后删除文件

                #region 复制文件夹
                
                DirectoryInfo sourceDir = new System.IO.DirectoryInfo(destFilePath);
                //处理文件夹
                foreach (var item in sourceDir.GetDirectories())    //一级目录
                {
                    foreach (var childDir in item.GetDirectories()) //二级目录
                    {
                        if (childDirName.Equals("文件夹名", StringComparison.CurrentCultureIgnoreCase))
                        {
                            CopyDirectory(childFullName, destDirName);   //复制文件夹
                        }
                    }
                }

                #endregion
            }

            #endregion
View Code


复制文件夹:

技术分享
/// <summary>
        /// 复制文件夹
        /// </summary>
        /// <param name="sourceDirName">源文件</param>
        /// <param name="destDirName">目标文件</param>
        private void CopyDirectory(string sourceDirName, string destDirName)
        {
            try
            {
                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                    System.IO.File.SetAttributes(destDirName, System.IO.File.GetAttributes(sourceDirName));
                }

                if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar) //  =="\\"
                {
                    destDirName = destDirName + Path.DirectorySeparatorChar;
                }
                string[] files = Directory.GetFiles(sourceDirName);
                foreach (string file in files)
                {
                    if (System.IO.File.Exists(destDirName + Path.GetFileName(file)))
                        continue;
                    System.IO.File.Copy(file, destDirName + Path.GetFileName(file), true);
                    System.IO.File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal);
                    //total++;
                }

                string[] dirs = Directory.GetDirectories(sourceDirName);//包括路径
                foreach (string dir in dirs)
                {
                    CopyDirectory(dir, destDirName + Path.GetFileName(dir));
                }
            }
            catch (Exception ex)
            {
                //StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt", true);    //System.Web.Providers.Entities
                //sw.Write(ex.Message + "     " + DateTime.Now + "\r\n");
                //sw.Close();
            }

        }
View Code

 

文件属性:

技术分享
C#遍历指定文件夹中的所有文件 
DirectoryInfo TheFolder=new DirectoryInfo(folderFullName);
//遍历文件夹
foreach(DirectoryInfo NextFolder in TheFolder.GetDirectories())
   this.listBox1.Items.Add(NextFolder.Name);
//遍历文件
foreach(FileInfo NextFile in TheFolder.GetFiles())
   this.listBox2.Items.Add(NextFile.Name); 

===================================================================
 
如何获取指定目录包含的文件和子目录
    1. DirectoryInfo.GetFiles():获取目录中(不包含子目录)的文件,返回类型为FileInfo[],支持通配符查找;
    2. DirectoryInfo.GetDirectories():获取目录(不包含子目录)的子目录,返回类型为DirectoryInfo[],支持通配符查找;
    3. DirectoryInfo. GetFileSystemInfos():获取指定目录下(不包含子目录)的文件和子目录,返回类型为FileSystemInfo[],支持通配符查找;
如何获取指定文件的基本信息;
    FileInfo.Exists:获取指定文件是否存在;
    FileInfo.Name,FileInfo.Extensioin:获取文件的名称和扩展名;
    FileInfo.FullName:获取文件的全限定名称(完整路径);
    FileInfo.Directory:获取文件所在目录,返回类型为DirectoryInfo;
    FileInfo.DirectoryName:获取文件所在目录的路径(完整路径);
    FileInfo.Length:获取文件的大小(字节数);
    FileInfo.IsReadOnly:获取文件是否只读;
    FileInfo.Attributes:获取或设置指定文件的属性,返回类型为FileAttributes枚举,可以是多个值的组合
    FileInfo.CreationTime、FileInfo.LastAccessTime、FileInfo.LastWriteTime:分别用于获取文件的创建时间、访问时间、修改时间;
View Code

 C#文件及文件夹操作示例  http://www.cnblogs.com/terer/articles/1514601.html

技术分享
//1.---------文件夹创建、移动、删除---------

//创建文件夹
Directory.CreateDirectory(Server.MapPath("a"));
Directory.CreateDirectory(Server.MapPath("b"));
Directory.CreateDirectory(Server.MapPath("c"));
//移动b到a
Directory.Move(Server.MapPath("b"), Server.MapPath("a\\b"));
//删除c
Directory.Delete(Server.MapPath("c"));

//2.---------文件创建、复制、移动、删除---------

//创建文件
//使用File.Create创建再复制/移动/删除时会提示:文件正由另一进程使用,因此该进程无法访问该文件
//改用 FileStream 获取 File.Create 返回的 System.IO.FileStream 再进行关闭就无此问题
FileStream fs;
fs = File.Create(Server.MapPath("a.txt"));
fs.Close();
fs = File.Create(Server.MapPath("b.txt"));
fs.Close();
fs = File.Create(Server.MapPath("c.txt"));
fs.Close();
//复制文件
File.Copy(Server.MapPath("a.txt"), Server.MapPath("a\\a.txt"));
//移动文件
File.Move(Server.MapPath("b.txt"), Server.MapPath("a\\b.txt"));
File.Move(Server.MapPath("c.txt"), Server.MapPath("a\\c.txt"));
//删除文件
File.Delete(Server.MapPath("a.txt"));

//3.---------遍历文件夹中的文件和子文件夹并显示其属性---------

if(Directory.Exists(Server.MapPath("a")))
{
    //所有子文件夹
    foreach(string item in Directory.GetDirectories(Server.MapPath("a")))
    {
        Response.Write("<b>文件夹:" + item + "</b><br/>");
        DirectoryInfo directoryinfo = new DirectoryInfo(item);
        Response.Write("名称:" + directoryinfo.Name + "<br/>");
        Response.Write("路径:" + directoryinfo.FullName + "<br/>");
        Response.Write("创建时间:" + directoryinfo.CreationTime + "<br/>");
        Response.Write("上次访问时间:" + directoryinfo.LastAccessTime + "<br/>");
        Response.Write("上次修改时间:" + directoryinfo.LastWriteTime + "<br/>");
        Response.Write("父文件夹:" + directoryinfo.Parent + "<br/>");
        Response.Write("所在根目录:" + directoryinfo.Root + "<br/>");
        Response.Write("<br/>");
    }

    //所有子文件
    foreach (string item in Directory.GetFiles(Server.MapPath("a")))
    {
        Response.Write("<b>文件:" + item + "</b><br/>");
        FileInfo fileinfo = new FileInfo(item);
        Response.Write("名称:" + fileinfo.Name + "<br/>");
        Response.Write("扩展名:" + fileinfo.Extension +"<br/>");
        Response.Write("路径:" + fileinfo.FullName +"<br/>");
        Response.Write("大小:" + fileinfo.Length +"<br/>");
        Response.Write("创建时间:" + fileinfo.CreationTime +"<br/>");
        Response.Write("上次访问时间:" + fileinfo.LastAccessTime +"<br/>");
        Response.Write("上次修改时间:" + fileinfo.LastWriteTime +"<br/>");
        Response.Write("所在文件夹:" + fileinfo.DirectoryName +"<br/>");
        Response.Write("文件属性:" + fileinfo.Attributes +"<br/>");
        Response.Write("<br/>");
    }
}

//4.---------文件读写---------

if (File.Exists(Server.MapPath("a\\a.txt")))
{
    StreamWriter streamwrite = new StreamWriter(Server.MapPath("a\\a.txt"));
    streamwrite.WriteLine("木子屋");
    streamwrite.WriteLine("http://www.mzwu.com/");
    streamwrite.Write("2008-04-13");
    streamwrite.Close();

    StreamReader streamreader = new StreamReader(Server.MapPath("a\\a.txt"));
    Response.Write(streamreader.ReadLine());
    Response.Write(streamreader.ReadToEnd());
    streamreader.Close();
}
View Code

 

C# 压缩 解压 复制文件夹

标签:

原文地址:http://www.cnblogs.com/love201314/p/5639750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!