To save a string variable to a zip file, use one of the following methods:
The following code shows both methods. In this example, the code for the OpenWriter method is shown in the button1_Click event. The code for the MemoryStream method is shown in the button2_Click event.
Make sure to add these using statements at the top of the code:
C# |
Copy Code
|
---|---|
using C1.C1Zip; using Microsoft.Win32; using System.IO; |
C# |
Copy Code
|
---|---|
public partial class MainWindow : Window { private string shakespeareText = ""; private C1ZipFile zipFile = null; public MainWindow() { InitializeComponent(); shakespeareText = "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."; zipFile = new C1ZipFile(); } private void button1_Click(object sender, RoutedEventArgs e) { SaveFileDialog dlgSaveFile = new SaveFileDialog(); dlgSaveFile.Filter = "Zip Files (*.zip) | *.zip"; if (dlgSaveFile.ShowDialog() == true) { zipFile.Create(dlgSaveFile.OpenFile()); } // Method 1: OpenWriter. Stream stream = zipFile.Entries.OpenWriter("Shakespeare.txt", true); C1ZStreamWriter sw = new C1ZStreamWriter(stream); byte[] text = System.Text.Encoding.Unicode.GetBytes(shakespeareText); sw.Write(text, 0, text.Length); sw.Flush(); stream.Close(); } private void button2_Click(object sender, RoutedEventArgs e) { SaveFileDialog dlgSaveFile = new SaveFileDialog(); dlgSaveFile.Filter = "Zip Files (*.zip) | *.zip"; if (dlgSaveFile.ShowDialog() == true) { zipFile.Create(dlgSaveFile.OpenFile()); } // Method 2: Memory Stream. Stream stream = new MemoryStream(); C1ZStreamWriter sw = new C1ZStreamWriter(stream); byte[] text = System.Text.Encoding.Unicode.GetBytes(shakespeareText); sw.Write(text, 0, text.Length); sw.Flush(); stream.Position = 0; zipFile.Entries.Add(stream, "Shakespeare2.txt"); stream.Close(); } |