命名空间: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");

解压:

                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
//获得目录下所有文件和子目录
使用DirectoryInfo类的GetFileSystemInfos()方法。 //获得目录下所有目录
string[] dirs = Directory.GetDirectories(你的目录的完整路径, "*", SearchOption.AllDirectories);
//获得目录下所有文件(包括该目录下的子目录的文件)
string[] dirs1 = Directory.GetFiles(你的目录的完整路径, "*.*", SearchOption.AllDirectories);
//该目录下的子目录和文件
var fileEntrys = System.IO.Directory.GetFileSystemEntries(filePath);
//获得一个目录下所有文件
string[] strNames = Directory.GetFiles(你的目录的完整路径);

目录下的子目录和文件

using ICSharpCode.SharpZipLib.Zip; 压缩文件

       /// <summary>
/// ZIP压缩单个文件
/// </summary>
/// <param name="sFileToZip">需要压缩的文件(绝对路径)</param>
/// <param name="sZippedPath">压缩后的文件路径(绝对路径)</param>
/// <param name="sZippedFileName">压缩后的文件名称(文件名,默认 同源文件同名)</param>
/// <param name="nCompressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param>
/// <param name="nBufferSize">缓存大小(每次写入文件大小,默认 2048)</param>
/// <param name="bEncrypt">是否加密(默认 加密)</param>
/// <param name="sPassword">密码(设置加密时生效。默认密码为"123")</param>
public static string ZipFile(string sFileToZip, string sZippedPath, string sZippedFileName = "", int nCompressionLevel = , int nBufferSize = , bool bEncrypt = true,string sPassword="")
{
if (!File.Exists(sFileToZip))
{
return null;
}
string sZipFileName = string.IsNullOrEmpty(sZippedFileName) ? sZippedPath + "\\" + new FileInfo(sFileToZip).Name.Substring(, new FileInfo(sFileToZip).Name.LastIndexOf('.')) + ".zip" : sZippedPath + "\\" + sZippedFileName + ".zip";
using (FileStream aZipFile = File.Create(sZipFileName))
{
using (ZipOutputStream aZipStream = new ZipOutputStream(aZipFile))
{
using (FileStream aStreamToZip = new FileStream(sFileToZip, FileMode.Open, FileAccess.Read))
{
string sFileName = sFileToZip.Substring(sFileToZip.LastIndexOf("\\") + );
ZipEntry ZipEntry = new ZipEntry(sFileName);
if (bEncrypt)
{
aZipStream.Password = sPassword;
}
aZipStream.PutNextEntry(ZipEntry);
aZipStream.SetLevel(nCompressionLevel);
byte[] buffer = new byte[nBufferSize];
int sizeRead = ;
try
{
do
{
sizeRead = aStreamToZip.Read(buffer, , buffer.Length);
aZipStream.Write(buffer, , sizeRead);
}
while (sizeRead > );
}
catch (Exception ex)
{
throw ex;
}
aStreamToZip.Close();
}
aZipStream.Finish();
aZipStream.Close();
}
aZipFile.Close();
}
return sZipFileName;
}

ZIP压缩单个文件

https://www.cnblogs.com/xuhongfei/p/5604193.html

http://www.cnblogs.com/ForRickHuan/p/7348221.html

复制文件夹:

/// <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 - ] != 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();
} }

文件属性:

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); =================================================================== 如何获取指定目录包含的文件和子目录
. DirectoryInfo.GetFiles():获取目录中(不包含子目录)的文件,返回类型为FileInfo[],支持通配符查找;
. DirectoryInfo.GetDirectories():获取目录(不包含子目录)的子目录,返回类型为DirectoryInfo[],支持通配符查找;
. 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:分别用于获取文件的创建时间、访问时间、修改时间;

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();
}

C#操作目录和文件  http://www.cnblogs.com/wanghonghu/archive/2012/07/04/2574579.html

zip文件的创建、读写和更新:  http://www.cnblogs.com/tcjiaan/p/4877020.html

动态生成zip文件: http://www.cnblogs.com/tcjiaan/p/4892578.html

C# 压缩 解压 复制文件夹,文件的操作的更多相关文章

  1. Linux压缩解压 tar.gz格式的文件.查看tomcat是否运行

    tar命令详解 -c: 建立压缩档案 -x:解压 -t:查看内容 -r:向压缩归档文件末尾追加文件 -u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用 ...

  2. 【转载】.NET压缩/解压文件/夹组件

    转自:http://www.cnblogs.com/asxinyu/archive/2013/03/05/2943696.html 阅读目录 1.前言 2.关于压缩格式和算法的基础 3.几种常见的.N ...

  3. linux查看文件夹大小,备份文件夹zip压缩解压

    linux查看文件夹大小,备份文件夹zip压缩解压 du -sh : 查看当前目录总共占的容量.而不单独列出各子项占用的容量 du -lh --max-depth=1 : 查看当前目录下一级子文件和子 ...

  4. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  5. android压缩解压zip文件

    网上各种方法的收集: 1.上次写了个解压缩功能,但有局限性,比如压缩文件xx.zip 里包括子目录的情况下,执行上次解压缩的功能就不能实现我们想要的效果,于是在网上参考了一下java的解压缩功能.对上 ...

  6. huffman压缩解压文件【代码】

    距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...

  7. 【.Net Core】ZipFile类--文件的压缩解压

    NuGet引用官网自带的System.IO.Compression.ZipFile; var filename = "测试压缩解压文件"; var path = Directory ...

  8. (转载)C#压缩解压zip 文件

    转载之: C#压缩解压zip 文件 - 大气象 - 博客园http://www.cnblogs.com/greatverve/archive/2011/12/27/csharp-zip.html C# ...

  9. tar 解压某个指定的文件或者文件夹

    1. 先查看压缩文档中有那些文件,如果都不清楚文件内容,然后就直接解压,这个是不可能的 使用#tar -tf 压缩包名称,可以查看压缩包内容 2.解压某个文件 tar -zxvf zabbix.tar ...

随机推荐

  1. Metasploit 读书笔记-神器Meterpreter

    一、基本命令 截屏 screenshot 2.获取系统平台信息 sysinfo 3.进程信息 ps 4.获取键盘记录 查看进程信息ps--migrate将会话迁移至explorer.exe进程空间中- ...

  2. 爬取腾讯课堂IT-互联网分类的的课程信息存入csv文件

    标签(空格分隔): python from urllib.request import urlopen from bs4 import BeautifulSoup #获取IT-互联网分类每页的课程的链 ...

  3. phaser小游戏框架学习(二)

    今天继续学习phaser.js.上周写的学习教程主要内容是创建游戏场景,游戏中的显示对象,按钮对象的使用以及如何在不同屏幕大小中完美适配.这篇博客以介绍游戏榜单的渲染更新为主. 代码地址:https: ...

  4. Jmeter解决乱码问题

    一.设置编码方式utf-8并勾选编码 适用场景:参数中含有中文或乱码 二.增加beanshell脚本 添加BeanShell PostProcessor或者BeanShell Sampler,输入代码 ...

  5. php 读取excel文件

    首先下载插件PHPExcel (PHPExcel-1.8),以tp5框架为例,将该文件放在verdor文件夹下.然后引入IOFactory文件. 1.读取文件的部分内容(用于固定格式) public ...

  6. 【模板】文艺平衡树(Splay) 区间翻转 BZOJ 3223

    您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作:翻转一个区间,例如原有序序列是5 4 3 2 1,翻转区间是[2,4]的话,结果是5 2 3 4 1 N,M<= ...

  7. springcloud系列二 搭建注册中心启动

    创建modul 然后就创建完成了 添加yml文件: server: port: eureka: client: register-with-eureka: false #单机版建议设置为false,设 ...

  8. sharepoint_study_12

    描述:SharePoint新建Web应用程序时提示如下错误: 解决: 1. Go to IIS 2. Select the DefaultAppPool and Go to the Advanced ...

  9. java Sprint boot 学习之一

    <properties> <project.build.sourceEncoding>UTF-</project.build.sourceEncoding> < ...

  10. linux 的 sftp 和 scp

    ====================================== 作者: wxy0327(http://wxy0327.itpub.net) 发表于: 2006.12.07 13:19 分 ...