how to compress and uncompress a text file - c#

I am having two problems
My problems are
My file name is 20110505.txt , and it is compressing a zip file name as -> 20110505.txt.zip
But I need after compressing this file 20110505.txt as --> 20110505.zip only.
I am using this dll
using System.IO.Compression;
Here is my code for compress,
1)is my text format
string path = DayDestination + "\\" + txtSelectedDate.Text + ".txt";
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(fi.FullName + ".zip"))
//using (FileStream outFile = File.Create( fi.Name+ ".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());
}
}
}
}
}
If my zip file name is 20110505.zip after uncompressing i want my file name to be 20110505.txt . after uncomressing the zip file to text file i want to delete the zip file after compressing
string Path2 = (string)(Application.StartupPath + "\\TEMP\\" + "\\" + name_atoz);
DirectoryInfo di = new DirectoryInfo(Path2);
FileInfo fi = new FileInfo(Path2);
Compress(fi);
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);
}
}
}
}
I want this because i am creating a project which reads the text file .
Is there any suggestion for my problem.
Thanks In Advance

As Mitch pointed out in the comments above, the problem seems to be with your file name being used for the zip file. You include the FullName, but that has the .txt at the end. Trim that off and you should have what you want.
The line I'm talking about is this one:
using (FileStream outFile = File.Create(fi.FullName + ".zip"))
A simple way to fix it would be as follows:
using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ".zip"))
To delete your zip file after you decompress it, put the following line in your Decompress method as the very last line (outside your outer-most using statement):
File.Delete(fi);
You probably want to wrap that in a try-catch but this is the basic code to run. Here is an article on how to delete a file safely:
http://www.dotnetperls.com/file-delete

Related

Using MemoryStream and DotNetZip to zip a json file

I have a JSON file created, and I am going to zip it using DotNetZip.
Using with StreamWriter to zip it is working, if I try to use MemoryStream it will not working.
StreamWriter :
sw = new StreamWriter(assetsFolder + #"manifest.json");
sw.Write(strManifest);
sw.Close();
zip.AddFile(Path.Combine(assetsFolder, "manifest.json"), "/");
zip.AddFile(Path.Combine(assetsFolder, "XXXXXXX"), "/");
zip.Save(outputStream);
MemoryStream :
var manifestStream = GenerateStreamFromString(strManifest);
public static Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
zip.AddEntry("manifest.json", manifestStream);
zip.AddFile(Path.Combine(assetsFolder, "XXXXXXX"), "/");
zip.Save(outputStream);
I must using the .JSON file type to zip it, Can any one told me where have a mistake?
To create a Gzipped Json you need to use GZipStream. Try method below.
https://www.dotnetperls.com/gzipstream
GZipStream compresses data. It saves data efficiently—such as in
compressed log files. We develop a utility method in the C# language
that uses the System.IO.Compression namespace. It creates GZIP files.
It writes them to the disk.
public static void CompressStringToFile(string fileName, string value)
{
// A.
// Write string to temporary file.
string temp = Path.GetTempFileName();
File.WriteAllText(temp, value);
// B.
// Read file into byte array buffer.
byte[] b;
using (FileStream f = new FileStream(temp, FileMode.Open))
{
b = new byte[f.Length];
f.Read(b, 0, (int)f.Length);
}
// C.
// Use GZipStream to write compressed bytes to target file.
using (FileStream f2 = new FileStream(fileName, FileMode.Create))
using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
{
gz.Write(b, 0, b.Length);
}
}

How to use filestream for copying files in c#

I want to copy a file from one folder to another folder using filestream.How this can be achived.when I try to use file.copy I was getting this file is using by another process, to avoid this I want to use file stream using c#. Can some one provide a sample for copying a file from one folder to another.
for copying i used below code :-
public static void Copy(string inputFilePath, string outputFilePath)
{
int bufferSize = 1024 * 1024;
using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite))
//using (FileStream fs = File.Open(<file-path>, FileMode.Open, FileAccess.Read, FileShare.Read))
{
FileStream fs = new FileStream(inputFilePath, FileMode.Open, FileAccess.ReadWrite);
fileStream.SetLength(fs.Length);
int bytesRead = -1;
byte[] bytes = new byte[bufferSize];
while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
}
}
}
You can use Stream.CopyTo method to copy the file like below:
public static string CopyFileStream(string outputDirectory, string inputFilePath)
{
FileInfo inputFile = new FileInfo(inputFilePath);
using (FileStream originalFileStream = inputFile.OpenRead())
{
var fileName = Path.GetFileName(inputFile.FullName);
var outputFileName = Path.Combine(outputDirectory, fileName);
using (FileStream outputFileStream = File.Create(outputFileName))
{
originalFileStream.CopyTo(outputFileStream);
}
return outputFileName;
}
}
string fileName = "Mytest.txt";
string sourcePath = #"C:\MyTestPath";
string targetPath = #"C:\MyTestTarget";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);

How to make different names of file and archive in GZipStream compression?

I have a file in a current directory, which name is firstName. I want to create an archive with this file (name of file have to stay). The archive name have to be an archiveName. But when I use my code I get an archive with the rigth name but the name of file in it was changed. How can I fix it?
public static void Compress(string firstName, string secondName)
{
FileInfo fileToCompress = new FileInfo(firstName);
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) &
FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(secondName))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream,
CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
FileInfo info = new FileInfo(secondName);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
}
}
}
GZipStream isn't a ZIP file; it's straight-up stream compression.
It has no notion of files or names; it just compresses bytes.
You're looking for the ZipArchive class.

DeflateStream / GZipStream to CryptoStream and vice versa

I want to to compress and encrypt a file in one go by using this simple code:
public void compress(FileInfo fi, Byte[] pKey, Byte[] pIV)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Create the compressed encrypted file.
using (FileStream outFile = File.Create(fi.FullName + ".pebf"))
{
using (CryptoStream encrypt = new CryptoStream(outFile, Rijndael.Create().CreateEncryptor(pKey, pIV), CryptoStreamMode.Write))
{
using (DeflateStream cmprss = new DeflateStream(encrypt, CompressionLevel.Optimal))
{
// Copy the source file into the compression stream.
inFile.CopyTo(cmprss);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
The following lines will restore the encrypted and compressed file back to the original:
public void decompress(FileInfo fi, Byte[] pKey, Byte[] pIV)
{
// 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 (CryptoStream decrypt = new CryptoStream(inFile, Rijndael.Create().CreateDecryptor(pKey, pIV), CryptoStreamMode.Read))
{
using (DeflateStream dcmprss = new DeflateStream(decrypt, CompressionMode.Decompress))
{
// Copy the uncompressed file into the output stream.
dcmprss.CopyTo(outFile);
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
}
This works also with GZipStream.
A decompressing stream is expected to be read from, not written to. (unlike a CryptoStream, which supports all four combinations of read/write and encrypt/decrypt)
You should create the DeflateStream around a CryptoStreamMode.Read stream around the input file, then copy from that directly to the output stream.

How to read a text file path after extracting the zip file from FTP

1) I am having a problem in reading a text file from my given path .
2) When i download the zip file from ftp i extracted it my extracting is working fine ,
3) The problem is when i download the file from ftp the file which i download is zip file i extract it to a text file and delete the zip file after extracting it and when i
try to read text file from the given path, the path reads the zip file not a text file
4) the code i am using for FTP and extracting the zipfile is,
private void DownloadMonth(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + ftpMonth + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = true;
reqFTP.UsePassive = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long c1 = response.ContentLength;
int bufferSize = 2048000;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
string Path1 = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_" + "\\" + fileName);
DirectoryInfo di = new DirectoryInfo(Path1);
FileInfo fi = new FileInfo(Path1);
Decompress(fi);
File.Delete(Path1);
}
catch (Exception ex)
{
}
}
Decompress Code
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(fi.FullName + ""))
//using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ""))
using (FileStream outFile = File.Create(origName + ".txt"))
{
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);
}
}
}
}
The code i use to download the text file from FTP and read the text file is
private void button1_Click(object sender, EventArgs e)
{
this.DownloadMonth(a, name_Month);
string Path1 = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_" + "\\" + name_Month);
StreamReader reader1 = File.OpenText(Path1);
string str = reader1.ReadToEnd();
reader1.Close();
reader1.Dispose();
}
There would be a great appreciation if someone can solve my problem.
Thanks In Advance
It looks like you're trying to read the binary file from your button1_Click method, instead of the text file. That's just a matter of giving it the wrong filename. You could try just using:
string Path1 = Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_\\"
+ name_Month + ".txt";
(in button1_Click)
... but really you should be able to diagnose what's going wrong yourself:
Is the file being downloaded correctly?
Is the decompression working?
Does the text file look okay afterwards (on the file system)?
If everything's working up to that point, then the download and decompression code is irrelevant, and it's obviously just the reading part in the click handler which is failing. If the text file isn't being created properly, then obviously something is wrong earlier in the process.
It's important to be able to diagnose this sort of thing yourself - you've got a clear 3-step process, and the results of that process should be easy to find just by looking on the file system, so the first thing to do is work out which bit is failing, and only look closely at that.
As an aside, in various places you're manually calling Close on things like streams and readers. Don't do that - use a using statement instead. You should also look at File.ReadAllText as a simpler alternative for reading the whole of a text file.
try string Path1 = origName + ".txt" in button click

Categories