如何解压压缩文件到一个文本扩展
问题描述:
可能重复:
how to read a *.file
how to compress and uncompress a text file如何解压压缩文件到一个文本扩展
嗨,
我有在解压缩zip文件到一个问题一个文本文件,
当我压缩该文本文件为zip文件(EX-20110530.txt到20110530.zip)。我代码被压缩我使用的文本文件压缩到压缩文件的代码是
string path = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_atoz" + "\\" + name_atoz);
StreamWriter Strwriter = new StreamWriter(path);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo fi = new FileInfo(path);
Compress(fi);
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Name != ".zip")
{
// Create the compressed file.
using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ".zip"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
这个代码创建一个zip文件,当我解压缩文件时,它会创建一个名为20110530而不是20110530.txt的文件。
我要的文件是解压缩与20110530.txt格式
我用它来解压缩文件的代码是
public static void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
//Create the decompressed file.
using (FileStream outFile = File.Create(origName))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
//Copy the decompression stream into the output file.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
{
outFile.Write(buffer, 0, numRead);
}
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
任何人都可以请帮助我,
在此先感谢。
答
在我看来,这条线:
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
删除字符串中的扩展,但在创建未压缩的流当您使用该行。
using (FileStream outFile = File.Create(origName))
相反,使用这样的:
using (FileStream outFile = File.Create(origName + ".txt"))
,并应创建一个TXT
扩展的未压缩的文件。
答
这是因为您在压缩文件时删除扩展名,使其变为20110530.zip
而不是20110530.txt.zip
。解压缩文件的代码使用.zip
之前的所有文件作为文件名,所以自然而然地,您将以20110530
而不是20110530.txt
结束。
答
确保当您在创建一个文件解压
//Create the decompressed file.
using (FileStream outFile = File.Create(origName)) // <<<-- here
很显然,你没有写这个代码,包括原始文件扩展名。您是否阅读过解压缩代码中的注释? – svick 2011-06-05 13:17:35
它越来越好,但您应该将代码添加到现有问题中,而不是发布新问题。 – 2011-06-05 13:19:33
你已经提出了同样的问题3次。请停止! – 2011-06-05 13:21:17