To save a string variable to a zip file, use one of the following methods:
• C1ZipEntryCollection.OpenWriter method
Use the OpenWriter method to get a stream writer, write the string into it, and then close it. The data is compressed as you write it into the stream, and the whole stream is saved into the zip file when you close it.
• MemoryStream method
Use a MemoryStream method; write the data into it, and then add the stream to the zip file. Note that this method requires a little more work than the OpenWriter method, but is still very manageable.
The following code shows both methods. Add the code to the Button_Click event:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = "Shall I compare thee to a summer's day? " + "Thou art more lovely and more temperate. " + "Rough winds do shake the darling buds of May, " + "And summer's lease hath all too short a date."
Dim zipFile As New C1ZipFile()
zipFile.Create("c:\temp\strings.zip")
' Method 1: OpenWriter.
Dim stream As Stream = zipFile.Entries.OpenWriter("Shakespeare.txt", True)
Dim sw As New C1ZStreamWriter(stream)
sw.Write(str)
sw.Close()
' Method 2: Memory Stream.
stream = New MemoryStream()
sw = New C1ZStreamWriter(stream)
sw.Write(str)
sw.Flush()
stream.Position = 0
zipFile.Entries.Add(stream, "Shakespeare2.txt")
stream.Close()
End Sub
•C#
private void button1_Click(object sender, System.EventArgs e)
{
string str = "Shall I compare thee to a summer's day? " +
"Thou art more lovely and more temperate. " +
"Rough winds do shake the darling buds of May, " +
"And summer's lease hath all too short a date.";
C1ZipFile zipFile = new C1ZipFile();
zipFile.Create(@"c:\temp\strings.zip");
// Method 1: OpenWriter.
Stream stream = zipFile.Entries.OpenWriter("Shakespeare.txt", true);
C1ZStreamWriter sw = new C1ZStreamWriter(stream);
sw.Write(str);
sw.Close();
// Method 2: Memory Stream.
stream = new MemoryStream();
sw = new C1ZStreamWriter(stream);
sw.Write(str);
sw.Flush();
stream.Position = 0;
zipFile.Entries.Add(stream, "Shakespeare2.txt");
stream.Close();
}