asp.NetC#ファイルを解凍する方法
個々のファイルを解凍するには、次の手順に従います.
using System.IO;
using System.IO.Compression;
string sourceFile=@"D:2.zip";
string destinationFile=@"D:1.txt";
private const long BUFFER_SIZE = 20480;
// make sure the source file is there
if (File.Exists ( sourceFile ))
{
FileStream sourceStream = null;
FileStream destinationStream = null;
GZipStream decompressedStream = null;
byte[] quartetBuffer = null;
try
{
// Read in the compressed source stream
sourceStream = new FileStream ( sourceFile, FileMode.Open );
// Create a compression stream pointing to the destiantion stream
decompressedStream = new DeflateStream ( sourceStream, CompressionMode.Decompress, true );
// Read the footer to determine the length of the destiantion file
quartetBuffer = new byte[4];
int position = (int)sourceStream.Length - 4;
sourceStream.Position = position;
sourceStream.Read ( quartetBuffer, 0, 4 );
sourceStream.Position = 0;
int checkLength = BitConverter.ToInt32 ( quartetBuffer, 0 );
byte[] buffer = new byte[checkLength + 100];
int offset = 0;
int total = 0;
// Read the compressed data into the buffer
while ( true )
{
int bytesRead = decompressedStream.Read ( buffer, offset, 100 );
if ( bytesRead == 0 )
break;
offset += bytesRead;
total += bytesRead;
}
// Now write everything to the destination file
destinationStream = new FileStream ( destinationFile, FileMode.Create );
destinationStream.Write ( buffer, 0, total );
// and flush everyhting to clean out the buffer
destinationStream.Flush ( );
}
catch ( ApplicationException ex )
{
Console.WriteLine(ex.Message, " :");
}
finally
{
// Make sure we allways close all streams
if ( sourceStream != null )
sourceStream.Close ( );
if ( decompressedStream != null )
decompressedStream.Close ( );
if ( destinationStream != null )
destinationStream.Close ( );
}
}
一括解凍(解凍クラスライブラリを呼び出す必要があります..ICSharpCode.SharpZipLib.dll)
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
namespace ZipLib
{
///
///
///
public static class ZIP
{
///
/// ZIP
///
/// ZIP
///
///
public static bool unzipFiles(string strZipFile, string strDir)
{
// ZIP
if (File.Exists(strZipFile))
{
//
bool bUnzipDir = false;
//
if (!Directory.Exists(strDir))
bUnzipDir = (Directory.CreateDirectory(strDir) != null);
else
bUnzipDir = true;
//
if (bUnzipDir)
{
// ZIP
ZipInputStream zipStream = new ZipInputStream(File.OpenRead(strZipFile));
if (zipStream != null)
{
ZipEntry zipEntry = null;
while ((zipEntry = zipStream.GetNextEntry()) != null)
{
string strUnzipFile = strDir + "//" + zipEntry.Name;
string strFileName = Path.GetFileName(strUnzipFile);
string strDirName = Path.GetDirectoryName(strUnzipFile);
//
if (!string.IsNullOrEmpty(strDirName))
Directory.CreateDirectory(strDirName);
//
if (!string.IsNullOrEmpty(strFileName))
{
//
FileStream unzipFileStream = new FileStream(strUnzipFile, FileMode.Create);
if (unzipFileStream != null)
{
byte[] buf = new byte[2048];
int size = 0;
while ((size = zipStream.Read(buf, 0, 2048)) > 0)
unzipFileStream.Write(buf, 0, size);
// Stream
unzipFileStream.Flush();
unzipFileStream.Close();
}
}
}
// ZIP
zipStream.Close();
//
return true;
}
}
}
return false;
}
}
}
上の2つはすべて解凍ファイルで、次に圧縮と解凍を1つのインスタンスに配置します.
最近、C#の圧縮と解凍に関する問題の解決方法を作ります.
ここでは主にフォルダに含まれるフォルダの解凍問題を解決します.
SharpZipLibをダウンロードdll、http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx中には最新の無料バージョンがあり、「Assemblies for.NET 1.1,.NET 2.0,.NET CF 1.0,.NET CF 2.0:.NET CF 2.0:Download[297 KB]」をクリックしてDownloadをダウンロードすることができ、解凍後に中には多くのフォルダがあり、異なるバージョンのため、私が使っているFW 2.0. あるいはここをクリックして当駅でダウンロードします.
SharpZipLibを参照dll、プロジェクトでプロジェクトを右クリック-->リファレンスの追加-->ブラウズ、追加するDLL->確認
ファイルの圧縮と解凍の2つのクラスを書き換えて、新しい2つのクラスの名前はZipFloClassです.cs,UnZipFloClass.csソースコードは以下の通りです.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
///
/// ZipFloClass
///
public class ZipFloClass
{
public void ZipFile(string strFile, string strZip)
{
if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
strFile += Path.DirectorySeparatorChar;
ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
s.SetLevel(6); // 0 - store only to 9 - means best compression
zip(strFile, s, strFile);
s.Finish();
s.Close();
}
private void zip(string strFile, ZipOutputStream s, string staticFile)
{
if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(strFile);
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
zip(file, s, staticFile);
}
else //
{
//
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string tempfile = file.Substring(staticFile.LastIndexOf("\") + 1);
ZipEntry entry = new ZipEntry(tempfile);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
}
}
}
using System;
using System.Data;
using System.Web;
using System.Text;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Checksums;
///
/// UnZipFloClass
///
public class UnZipFloClass
{
public string unZipFile(string TargetFile, string fileDir)
{
string rootFile = " ";
try
{
// (zip ),
ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
ZipEntry theEntry;
string path = fileDir;
//
string rootDir = " ";
//
while ((theEntry = s.GetNextEntry()) != null)
{
rootDir = Path.GetDirectoryName(theEntry.Name);
//
if (rootDir.IndexOf("\") >= 0)
{
rootDir = rootDir.Substring(0, rootDir.IndexOf("\") + 1);
}
string dir = Path.GetDirectoryName(theEntry.Name);
//
string fileName = Path.GetFileName(theEntry.Name);
//
if (dir != " " )
// ,
{
if (!Directory.Exists(fileDir + "\" + dir))
{
path = fileDir + "\" + dir;
//
Directory.CreateDirectory(path);
}
}
else if (dir == " " && fileName != "")
//
{
path = fileDir;
rootFile = fileName;
}
else if (dir != " " && fileName != "")
//
{
if (dir.IndexOf("\") > 0)
//
{
path = fileDir + "\" + dir;
}
}
if (dir == rootDir)
//
{
path = fileDir + "\" + rootDir;
}
// zip
// , 。
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(path + "\" + fileName);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
return rootFile;
}
catch (Exception ex)
{
return "1; " + ex.Message;
}
}
}
参照、新しいページを作成し、2つのボタンを追加し、ボタンにClickイベントを追加します.
ソースコードは以下の通りです.
protected void Button1_Click(object sender, EventArgs e)
{
string[] FileProperties = new string[2];
FileProperties[0] = "D:\unzipped\";//
FileProperties[1] = "D:\zip\a.zip"; //
ZipFloClass Zc = new ZipFloClass();
Zc.ZipFile(FileProperties[0], FileProperties[1]);
}
protected void Button2_Click(object sender, EventArgs e)
{
string[] FileProperties = new string[2];
FileProperties[0] = "D:\zip\b.zip";//
FileProperties[1] = "D:\unzipped\";//
UnZipFloClass UnZc = new UnZipFloClass();
UnZc.unZipFile(FileProperties[0], FileProperties[1]);
}
皆さんのaspについてお話ししたいと思います.Netプログラミングが役立ちます.