Is it possible to change file content directly in zip file? - c#

I have form with text box and customer wants to store all changes from this textbox to zip archive.
I am using http://dotnetzip.codeplex.com
and i have example of code:
using (ZipFile zip = new ZipFile())
{
zip.AddFile("text.txt");
zip.Save("Backup.zip");
}
And i dont want to create each time temp text.txt and zip it back.
Can I access text.txt as Stream inside zip file and save text there?

There is an example in DotNetZip that use a Stream with the method AddEntry.
String zipToCreate = "Content.zip";
String fileNameInArchive = "Content-From-Stream.bin";
using (System.IO.Stream streamToRead = MyStreamOpener())
{
using (ZipFile zip = new ZipFile())
{
ZipEntry entry= zip.AddEntry(fileNameInArchive, streamToRead);
zip.Save(zipToCreate); // the stream is read implicitly here
}
}
A little test using LinqPad shows that it is possible to use a MemoryStream to build the zip file
void Main()
{
UnicodeEncoding uniEncoding = new UnicodeEncoding();
byte[] firstString = uniEncoding.GetBytes("This is the current contents of your TextBox");
using(MemoryStream memStream = new MemoryStream(100))
{
memStream.Write(firstString, 0 , firstString.Length);
// Reposition the stream at the beginning (otherwise an empty file will be created in the zip archive
memStream.Seek(0, SeekOrigin.Begin);
using (ZipFile zip = new ZipFile())
{
ZipEntry entry= zip.AddEntry("TextBoxData.txt", memStream);
zip.Save(#"D:\temp\memzip.zip");
}
}
}

There is another DotNetZip method accepting a file path as an argument:
zip.RemoveEntry(entry);
zip.AddEntry(entry.FileName, text, ASCIIEncoding.Unicode);

Related

Is possible to create zip password protected file without first creating file, then zip it

I am writing data into text file and using below code,
await using var file = new StreamWriter(filePath);
foreach (var packet in resultPackets)
{
file.WriteLine(JsonConvert.SerializeObject(packet));
}
And I am using below code to zip the file with password protected using `DotNetZip,
using (ZipFile zip = new ZipFile())
{
zip.Password = "password";
zip.AddFile(filePath);
zip.Save(#"C:\tmp\data4.zip");
}
Is there a way to combined both, I want to create a file on the fly as password protected.
I don't
want to create first file with data, t
then create zip file from it
and delete the base file
Is this possible? Thanks!
Okay, so since this is still unanswered, here's a small program that does the job for me:
using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream))
{
// Insert your code in here, i.e.
//foreach (var packet in resultPackets)
//{
// streamWriter.WriteLine(JsonConvert.SerializeObject(packet));
//}
// ... instead I write a simple string.
streamWriter.Write("Hello World!");
// Make sure the contents from the StreamWriter are actually flushed into the stream, then seek the beginning of the stream.
streamWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
using (ZipFile zip = new ZipFile())
{
zip.Password = "password";
// Write the contents of the stream into a file that is called "test.txt"
zip.AddEntry("test.txt", stream);
// Save the archive.
zip.Save("test.zip");
}
}
Note how AddEntry does not create any form of temporary file. Instead, when the archive is saved, the contents of the stream are read and put into a compressed file within the archive. However, be aware that the whole content of the file are completely kept in memory before it the archive is written to the disk.

convert compress xmldocument as zip and get as byte array

I am building a XmlDocument in memory (I am not writing it to disk). I need to be able to create a zip archive that would contain the Xml file and then get the zip archive as byte array (all of this without actually writing/creating anything on the hard-disk). Is this possible?
I should mention that I am trying to do this in C#.
var buffer = new MemoryStream();
using (buffer)
using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create) )
{
var entry = zip.CreateEntry("content.xml", CompressionLevel.Optimal);
using (var stream = entry.Open())
{
xmlDoc.Save(stream);
}
}
var bytes = buffer.ToArray();

Convert byte[] to excel file (xlsx)

I need to convert a byte array into an excel file using C# to upload it in Sharepoint.
The following code read an input file from client as a byte array:
public object UploadFile(HttpPostedFile file)
{
byte[] fileData = null;
using (var binaryReader = new BinaryReader(file.InputStream))
{
fileData = binaryReader.ReadBytes(imageFile.ContentLength);
// convert fileData to excel
}
}
How can I do it?
It sounds like you're just after File.WriteAllBytes(path, contents). However, if the input file could be large, you may be better off using the Stream API:
using(var destination = File.Create(path)) {
file.InputStream.CopyTo(destination);
}
Edit: it looks like HttpPostedFile has a SaveAs method, so just:
file.SaveAs(path);

Compress a single file using C#

I am using .NET 4.5, and the ZipFile class works great if I am trying to zip up an entire directory with "CreateFromDirectory". However, I only want to zip up one file in the directory. I tried pointing to a specific file (folder\data.txt), but that doesn't work. I considered the ZipArchive class since it has a "CreateEntryFromFile" method, but it seems this only allows you to create an entry into an existing file.
Is there no way to simply zip up one file without creating an empty zipfile (which has its issues) and then using the ZipArchiveExtension's "CreateEntryFromFile" method?
**This is also assuming I am working on a company program which cannot use third-party add-ons at the moment.
example from:http://msdn.microsoft.com/en-us/library/ms404280%28v=vs.110%29.aspx
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
But if startPath were to be #"c:\example\start\myFile.txt;", it would throw an error that the directory is invalid.
Use the CreateEntryFromFile off a an archive and use a file or memory stream:
Using a filestream if you are fine creating the zip file and then adding to it:
using (FileStream fs = new FileStream(#"C:\Temp\output.zip",FileMode.Create))
using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create))
{
arch.CreateEntryFromFile(#"C:\Temp\data.xml", "data.xml");
}
Or if you need to do everything in memory and write the file once it is done, use a memory stream:
using (MemoryStream ms = new MemoryStream())
using (ZipArchive arch = new ZipArchive(ms, ZipArchiveMode.Create))
{
arch.CreateEntryFromFile(#"C:\Temp\data.xml", "data.xml");
}
Then you can write the MemoryStream to a file.
using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write)) {
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
ms.Close();
}
Using file (or any) stream:
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
{
var entry = zip.CreateEntry("file.txt");
entry.LastWriteTime = DateTimeOffset.Now;
using (var stream= File.OpenRead(#"c:\path\to\file.txt"))
using (var entryStream = entry.Open())
stream.CopyTo(entryStream);
}
or briefer:
// reference System.IO.Compression
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
zip.CreateEntryFromFile("file.txt", "file.txt");
make sure you add references to System.IO.Compression
Update
Also, check out the new dotnet API documentation for ZipFile and ZipArchive too. There are a few examples there. There is also a warning about referencing System.IO.Compression.FileSystem to use ZipFile.
To use the ZipFile class, you must reference the
System.IO.Compression.FileSystem assembly in your project.
The simplest way to get this working is to use a temporary folder.
FOR ZIPPING:
Create a temp folder
Move file to folder
Zip folder
Delete folder
FOR UNZIPPING:
Unzip archive
Move file from temp folder to your location
Delete temp folder
In .NET, there are quite a few ways to tackle the problem, for a single file. If you don't want to learn everything there, you can get an abstracted library, like SharpZipLib (long standing open source library), sevenzipsharp (requires 7zip libs underneath) or DotNetZip.
just use following code for compressing a file.
public void Compressfile()
{
string fileName = "Text.txt";
string sourcePath = #"C:\SMSDBBACKUP";
DirectoryInfo di = new DirectoryInfo(sourcePath);
foreach (FileInfo fi in di.GetFiles())
{
//for specific file
if (fi.ToString() == fileName)
{
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.Extension != ".gz")
{
// Create the compressed file.
using (FileStream outFile =
File.Create(fi.FullName + ".gz"))
{
using (GZipStream Compress =
new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into
// the compression stream.
inFile.CopyTo(Compress);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
}

c# dotnetzip memorystream with zip file

What I am trying to do in the code below is to open up a zip file from a memoryStream which has files within it that are created from memoryStream as well.
Note that I am using c# MVC as I have a return File...
memoryStream1 does have a length to it so not sure when I open up the archive.zip, it says
Excel cannot open payload.xlsx because the file format or file extenion is not valid.
Verify that the fle has not been corrupted and that the file extension matches
the format of the file.
The file extension is definitely xlsx so that can't be the problem. Am I going about this in the wrong way?
I have the following code:
var memoryStream1 = new MemoryStream();
gc.CreatePackage(memoryStream1);
var memoryStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddEntry("payload.xlsx", memoryStream1);
zip.Save(memoryStream);
}
memoryStream.Seek(0, 0);
return File(memoryStream, "application/octet-stream", "archive.zip");

Categories