c# 上傳壓縮包 解壓,遍歷資料夾和檔案

過朢發表於2024-03-11

<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:button ID="Button1" runat="server" text="上傳" OnClick="Button1_Click" />
</div>
</form>
</body>

引用 SharpCompress.dll

下載地址https://download.csdn.net/download/weixin_42020830/87737306?spm=1001.2014.3001.5503

protected void Button1_Click(object sender, EventArgs e)
{

//獲取客服端上載檔案的集合
HttpFileCollection HFC = System.Web.HttpContext.Current.Request.Files;
//將上傳壓縮包複製到指定路徑
string zipPath = Request.MapPath("~/UploadZipFile/" + Guid.NewGuid().ToString() + "");
if (!Directory.Exists(zipPath))//判斷資料夾是否存在
{
Directory.CreateDirectory(zipPath);//不存在則建立資料夾
}
string filePath = Path.Combine(zipPath, HFC[0].FileName);
HFC[0].SaveAs(filePath);
//解壓資料夾存放路徑
string newGuid = Guid.NewGuid().ToString();
string pathFile = Request.MapPath("~/UploadFile/" + newGuid + "");
if (!Directory.Exists(pathFile))//判斷資料夾是否存在
{
Directory.CreateDirectory(pathFile);//不存在則建立資料夾
}
string[] pathLen = pathFile.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
//解壓壓縮包
string[] valueLen = HFC[0].FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string lenValue = valueLen[valueLen.Length - 1];
string targetFile = zipPath + "\\" + HFC[0].FileName;

using (Stream stream =System.IO.File.OpenRead(targetFile))
{
var reader = ReaderFactory.Open(stream);
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
reader.WriteEntryToDirectory(pathFile, new ExtractionOptions { ExtractFullPath = true, Overwrite = true });
}
}
}
//遍歷檔案
public void getFileName( string path, int pathLen)
{
string[] valueLen = path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
DirectoryInfo root = new DirectoryInfo(path);
string recidFile = Guid.NewGuid().ToString("N").Substring(0, 25);
string name = valueLen[valueLen.Length - 1];//資料夾名
foreach (FileInfo f in root.GetFiles())
{
Console.WriteLine(f.Name);
}

}

相關文章