- Public Sub CreateMySqlCommand()
- Dim myCommand As New MySqlCommand()
- myCommand.CommandText = "SELECT * FROM Mytable ORDER BY id"
- myCommand.CommandType = CommandType.Text
- End Sub
-
-
- public void CreateMySqlCommand()
- {
- MySqlCommand myCommand = new MySqlCommand();
- myCommand.CommandText = "SELECT * FROM mytable ORDER BY id";
- myCommand.CommandType = CommandType.Text;
- }
-
-
- Public Sub CreateMySqlCommand()
- Dim myCommand As New MySqlCommand()
- myCommand.CommandType = CommandType.Text
- End Sub
-
-
- public void CreateMySqlCommand()
- {
- MySqlCommand myCommand = new MySqlCommand();
- myCommand.CommandType = CommandType.Text;
- }
-
-
- Public Sub CreateMySqlCommand()
- Dim mySelectQuery As String = "SELECT * FROM mytable ORDER BY id"
- Dim myConnectString As String = "Persist Security Info=False;database=test;server=myServer"
- Dim myCommand As New MySqlCommand(mySelectQuery)
- myCommand.Connection = New MySqlConnection(myConnectString)
- myCommand.CommandType = CommandType.Text
- End Sub
-
-
- public void CreateMySqlCommand()
- {
- string mySelectQuery = "SELECT * FROM mytable ORDER BY id";
- string myConnectString = "Persist Security Info=False;database=test;server=myServer";
- MySqlCommand myCommand = new MySqlCommand(mySelectQuery);
- myCommand.Connection = new MySqlConnection(myConnectString);
- myCommand.CommandType = CommandType.Text;
- }
-
-
- Public Sub CreateMySqlCommand(myConnection As MySqlConnection, _
- mySelectQuery As String, myParamArray() As MySqlParameter)
- Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
- myCommand.CommandText = "SELECT id, name FROM mytable WHERE age=@age"
- myCommand.UpdatedRowSource = UpdateRowSource.Both
- myCommand.Parameters.Add(myParamArray)
- Dim j As Integer
- For j = 0 To myCommand.Parameters.Count - 1
- myCommand.Parameters.Add(myParamArray(j))
- Next j
- Dim myMessage As String = ""
- Dim i As Integer
- For i = 0 To myCommand.Parameters.Count - 1
- myMessage += myCommand.Parameters(i).ToString() & ControlChars.Cr
- Next i
- Console.WriteLine(myMessage)
- End Sub
-
-
- public void CreateMySqlCommand(MySqlConnection myConnection, string mySelectQuery,
- MySqlParameter[] myParamArray)
- {
- MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
- myCommand.CommandText = "SELECT id, name FROM mytable WHERE age=@age";
- myCommand.Parameters.Add(myParamArray);
- for (int j=0; j<myParamArray.Length; j++)
- {
- myCommand.Parameters.Add(myParamArray[j]) ;
- }
- string myMessage = "";
- for (int i = 0; i < myCommand.Parameters.Count; i++)
- {
- myMessage += myCommand.Parameters[i].ToString() + "\n";
- }
- MessageBox.Show(myMessage);
- }
-
-
- Public Sub CreateMySqlCommand(myExecuteQuery As String, myConnection As MySqlConnection)
- Dim myCommand As New MySqlCommand(myExecuteQuery, myConnection)
- myCommand.Connection.Open()
- myCommand.ExecuteNonQuery()
- myConnection.Close()
- End Sub
-
-
- public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
- {
- MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
- myCommand.Connection.Open();
- myCommand.ExecuteNonQuery();
- myConnection.Close();
- }
-
-
- Public Sub CreateMySqlDataReader(mySelectQuery As String, myConnection As MySqlConnection)
- Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
- myConnection.Open()
- Dim myReader As MySqlDataReader
- myReader = myCommand.ExecuteReader()
- Try
- While myReader.Read()
- Console.WriteLine(myReader.GetString(0))
- End While
- Finally
- myReader.Close
- myConnection.Close
- End Try
- End Sub
-
-
- public void CreateMySqlDataReader(string mySelectQuery, MySqlConnection myConnection)
- {
- MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
- myConnection.Open();
- MMySqlDataReader myReader;
- myReader = myCommand.ExecuteReader();
- try
- {
- while(myReader.Read())
- {
- Console.WriteLine(myReader.GetString(0));
- }
- }
- finally
- {
- myReader.Close();
- myConnection.Close();
- }
- }
-
-
- Public Sub CreateMySqlCommand(myScalarQuery As String, myConnection As MySqlConnection)
- Dim myCommand As New MySqlCommand(myScalarQuery, myConnection)
- myCommand.Connection.Open()
- myCommand.ExecuteScalar()
- myConnection.Close()
- End Sub
-
-
- public void CreateMySqlCommand(string myScalarQuery, MySqlConnection myConnection)
- {
- MySqlCommand myCommand = new MySqlCommand(myScalarQuery, myConnection);
- myCommand.Connection.Open();
- myCommand.ExecuteScalar();
- myConnection.Close();
- }
-
-
- public:
- void CreateMySqlCommand(String* myScalarQuery, MySqlConnection* myConnection)
- {
- MySqlCommand* myCommand = new MySqlCommand(myScalarQuery, myConnection);
- myCommand->Connection->Open();
- myCommand->ExecuteScalar();
- myConnection->Close();
- }
-
-
-
- public sub PrepareExample()
- Dim cmd as New MySqlCommand("INSERT INTO mytable VALUES (@val)", myConnection)
- cmd.Parameters.Add( "@val", 10 )
- cmd.Prepare()
- cmd.ExecuteNonQuery()
-
- cmd.Parameters(0).Value = 20
- cmd.ExecuteNonQuery()
- end sub
-
-
- private void PrepareExample()
- {
- MySqlCommand cmd = new MySqlCommand("INSERT INTO mytable VALUES (@val)", myConnection);
- cmd.Parameters.Add( "@val", 10 );
- cmd.Prepare();
- cmd.ExecuteNonQuery();
-
- cmd.Parameters[0].Value = 20;
- cmd.ExecuteNonQuery();
- }
-
-
- Public Shared Function SelectRows(myConnection As String, mySelectQuery As String, myTableName As String) As DataSet
- Dim myConn As New MySqlConnection(myConnection)
- Dim myDataAdapter As New MySqlDataAdapter()
- myDataAdapter.SelectCommand = New MySqlCommand(mySelectQuery, myConn)
- Dim cb As SqlCommandBuilder = New MySqlCommandBuilder(myDataAdapter)
-
- myConn.Open()
-
- Dim ds As DataSet = New DataSet
- myDataAdapter.Fill(ds, myTableName)
-
- ' Code to modify data in DataSet here
-
- ' Without the MySqlCommandBuilder this line would fail.
- myDataAdapter.Update(ds, myTableName)
-
- myConn.Close()
- End Function 'SelectRows
-
-
- public static DataSet SelectRows(string myConnection, string mySelectQuery, string myTableName)
- {
- MySqlConnection myConn = new MySqlConnection(myConnection);
- MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
- myDataAdapter.SelectCommand = new MySqlCommand(mySelectQuery, myConn);
- MySqlCommandBuilder cb = new MySqlCommandBuilder(myDataAdapter);
-
- myConn.Open();
-
- DataSet ds = new DataSet();
- myDataAdapter.Fill(ds, myTableName);
-
- //code to modify data in DataSet here
-
- //Without the MySqlCommandBuilder this line would fail
- myDataAdapter.Update(ds, myTableName);
-
- myConn.Close();
-
- return ds;
- }
-
-
-
- Public Sub CreateSqlConnection()
- Dim myConnection As New MySqlConnection()
- myConnection.ConnectionString = "Persist Security Info=False;Username=user;Password=pass;database=test1;server=localhost;Connect Timeout=30"
- myConnection.Open()
- End Sub
-
-
- public void CreateSqlConnection()
- {
- MySqlConnection myConnection = new MySqlConnection();
- myConnection.ConnectionString = "Persist Security Info=False;Username=user;Password=pass;database=test1;server=localhost;Connect Timeout=30";
- myConnection.Open();
- }
-
-
- Public Sub CreateMySqlConnection()
- Dim myConnString As String = _
- "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass"
- Dim myConnection As New MySqlConnection( myConnString )
- myConnection.Open()
- MessageBox.Show( "Server Version: " + myConnection.ServerVersion _
- + ControlChars.NewLine + "Database: " + myConnection.Database )
- myConnection.ChangeDatabase( "test2" )
- MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion _
- + ControlChars.NewLine + "Database: " + myConnection.Database )
- myConnection.Close()
- End Sub
-
-
-
- public void CreateMySqlConnection()
- {
- string myConnString =
- "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass";
- MySqlConnection myConnection = new MySqlConnection( myConnString );
- myConnection.Open();
- MessageBox.Show( "Server Version: " + myConnection.ServerVersion
- + "\nDatabase: " + myConnection.Database );
- myConnection.ChangeDatabase( "test2" );
- MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion
- + "\nDatabase: " + myConnection.Database );
- myConnection.Close();
- }
-
-
- Public Sub CreateMySqlConnection(myConnString As String)
- Dim myConnection As New MySqlConnection(myConnString)
- myConnection.Open()
- MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _
- + ControlChars.Cr + "State: " + myConnection.State.ToString())
- myConnection.Close()
- End Sub
-
-
- public void CreateMySqlConnection(string myConnString)
- {
- MySqlConnection myConnection = new MySqlConnection(myConnString);
- myConnection.Open();
- MessageBox.Show("ServerVersion: " + myConnection.ServerVersion +
- "\nState: " + myConnection.State.ToString());
- myConnection.Close();
- }
-
- Name | -Default | -Description | -
---|---|---|
- Connect Timeout |
- 15 | -- The length of time (in seconds) to wait for a connection to the server before - terminating the attempt and generating an error. - | -
- Host |
- localhost | -
- |
-
Port | -3306 | -- The port MySQL is using to listen for connections. This value is ignored if the connection protocol - is anything but socket. - | -
Protocol | -socket | -
- Specifies the type of connection to make to the server. - pipe for a named pipe connection - unix for a Unix socket connection - memory to use MySQL shared memory - |
-
- CharSet |
- - | - Specifies the character set that should be used to encode all queries sent to the server. - Resultsets are still returned in the character set of the data returned. - | -
Logging | -false | -When true, various pieces of information is output to any configured TraceListeners. | -
Allow Batch | -true | -
- When true, multiple SQL statements can be sent with one command execution. - -Note- - Starting with MySQL 4.1.1, batch statements should be separated by the server-defined seperator character. - Commands sent to earlier versions of MySQL should be seperated with ';'. - |
-
Encrypt | -false | -- When true, SSL/TLS encryption is used for all data sent between the - client and server if the server has a certificate installed. Recognized values - are true, false, yes, and no. - | -
- Initial Catalog |
- mysql | -The name of the database to use intially | -
- Password |
- - | The password for the MySQL account being used. | -
Persist Security Info | -false | -- When set to false or no (strongly recommended), security-sensitive - information, such as the password, is not returned as part of the connection if - the connection is open or has ever been in an open state. Resetting the - connection string resets all connection string values including the password. - Recognized values are true, false, yes, and no. - | -
- User Id |
- - | The MySQL login account being used. | -
Shared Memory Name | -MYSQL | -The name of the shared memory object to use for communication if the connection protocol is set to memory. | -
Allow Zero Datetime | -false | -- True to have MySqlDataReader.GetValue() return a MySqlDateTime for date or datetime columns that have illegal values. - False will cause a DateTime object to be returned for legal values and an exception will be thrown for illegal values. - | -
Convert Zero Datetime | -false | -- True to have MySqlDataReader.GetValue() and MySqlDataReader.GetDateTime() - return DateTime.MinValue for date or datetime columns that have illegal values. - | -
- Pipe Name |
- mysql | -
- When set to the name of a named pipe, the MySqlConnection will attempt to connect to MySQL
- on that named pipe. This settings only applies to the Windows platform. - |
-
- Use Performance Monitor |
- false | -- Posts performance data that can be tracked using perfmon - | -
- Procedure Cache Size - | -25 | -- How many stored procedure definitions can be held in the cache - | -
- Ignore Prepare - | -true | -- Instructs the provider to ignore any attempts to prepare commands. This option - was added to allow a user to disable prepared statements in an entire application - without modifying the code. A user might want to do this if errors or bugs are - encountered with MySQL prepared statements. - | -
Use Procedure Bodies | -true | -- Instructs the provider to attempt to call the procedure without first resolving the metadata. This - is useful in situations where the calling user does not have access to the mysql.proc table. To - use this mode, the parameters for the procedure must be added to the command in the same order - as they appear in the procedure definition and their types must be explicitly set. - | -
Auto Enlist | -true | -- Indicates whether the connection should automatically enlist in the current transaction, - if there is one. - | -
Respect Binary Flags | -true | -- Indicates whether the connection should respect all binary flags sent to the client - as part of column metadata. False will cause the connector to behave like - Connector/Net 5.0 and earlier. - | -
BlobAsUTF8IncludePattern | -null | -- Pattern that should be used to indicate which blob columns should be treated as UTF-8. - | -
BlobAsUTF8ExcludePattern | -null | -- Pattern that should be used to indicate which blob columns should not be treated as UTF-8. - | -
Default Command Timeout | -30 | -- The default timeout that new MySqlCommand objects will use unless changed. - | -
Allow User Variables | -false | -- Should the provider expect user variables in the SQL. - | -
Interactive -or- Interactive Session | -false | -- Should this session be considered interactive? - | -
Functions Return String | -false | -- Set this option to true to force the return value of SQL functions to be string. - | -
Use Affected Rows | -false | -- Set this option to true to cause the affected rows reported to reflect only the - rows that are actually changed. By default, the number of rows that are matched - is returned. - | -
Name | -Default | -Description | -
---|---|---|
Connection Lifetime | -0 | -
- When a connection is returned to the pool, its creation time is compared with
- the current time, and the connection is destroyed if that time span (in seconds)
- exceeds the value specified by Connection Lifetime. This is useful in
- clustered configurations to force load balancing between a running server and a
- server just brought online.
- |
-
Max Pool Size | -100 | -The maximum number of connections allowed in the pool. | -
Min Pool Size | -0 | -The minimum number of connections allowed in the pool. | -
Pooling | -true | -- When true, the MySqlConnection object is drawn from the appropriate - pool, or if necessary, is created and added to the appropriate pool. Recognized - values are true, false, yes, and no. - | -
Connection Reset | -false | -- Specifies whether the database connection should be reset when being - drawn from the pool. Leaving this as false will yeild much faster - connection opens but the user should understand the side effects - of doing this such as temporary tables and user variables from the previous - session not being cleared out. - | -
Cache Server Properties | -false | -- Specifies whether the server variables are cached between pooled connections. - On systems where the variables change infrequently and there are lots of - connection attempts, this can speed up things dramatically. - | -
- Public Sub CreateConnection()
- Dim myConnection As New MySqlConnection()
- myConnection.ConnectionString = "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass"
- myConnection.Open()
- End Sub 'CreateConnection
-
-
- public void CreateConnection()
- {
- MySqlConnection myConnection = new MySqlConnection();
- myConnection.ConnectionString = "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass";
- myConnection.Open();
- }
-
-
- Public Sub CreateConnection()
- Dim myConnection As New MySqlConnection()
- myConnection.ConnectionString = "database=myDB;server=/var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass"
- myConnection.Open()
- End Sub 'CreateConnection
-
-
- public void CreateConnection()
- {
- MySqlConnection myConnection = new MySqlConnection();
- myConnection.ConnectionString = "database=myDB;server=/var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass";
- myConnection.Open();
- }
-
-
- Public Sub RunTransaction(myConnString As String)
- Dim myConnection As New MySqlConnection(myConnString)
- myConnection.Open()
-
- Dim myCommand As MySqlCommand = myConnection.CreateCommand()
- Dim myTrans As MySqlTransaction
-
- ' Start a local transaction
- myTrans = myConnection.BeginTransaction()
- ' Must assign both transaction object and connection
- ' to Command object for a pending local transaction
- myCommand.Connection = myConnection
- myCommand.Transaction = myTrans
-
- Try
- myCommand.CommandText = "Insert into Test (id, desc) VALUES (100, 'Description')"
- myCommand.ExecuteNonQuery()
- myCommand.CommandText = "Insert into Test (id, desc) VALUES (101, 'Description')"
- myCommand.ExecuteNonQuery()
- myTrans.Commit()
- Console.WriteLine("Both records are written to database.")
- Catch e As Exception
- Try
- myTrans.Rollback()
- Catch ex As MySqlException
- If Not myTrans.Connection Is Nothing Then
- Console.WriteLine("An exception of type " + ex.GetType().ToString() + _
- " was encountered while attempting to roll back the transaction.")
- End If
- End Try
-
- Console.WriteLine("An exception of type " + e.GetType().ToString() + _
- "was encountered while inserting the data.")
- Console.WriteLine("Neither record was written to database.")
- Finally
- myConnection.Close()
- End Try
- End Sub
-
-
- public void RunTransaction(string myConnString)
- {
- MySqlConnection myConnection = new MySqlConnection(myConnString);
- myConnection.Open();
-
- MySqlCommand myCommand = myConnection.CreateCommand();
- MySqlTransaction myTrans;
-
- // Start a local transaction
- myTrans = myConnection.BeginTransaction();
- // Must assign both transaction object and connection
- // to Command object for a pending local transaction
- myCommand.Connection = myConnection;
- myCommand.Transaction = myTrans;
-
- try
- {
- myCommand.CommandText = "insert into Test (id, desc) VALUES (100, 'Description')";
- myCommand.ExecuteNonQuery();
- myCommand.CommandText = "insert into Test (id, desc) VALUES (101, 'Description')";
- myCommand.ExecuteNonQuery();
- myTrans.Commit();
- Console.WriteLine("Both records are written to database.");
- }
- catch(Exception e)
- {
- try
- {
- myTrans.Rollback();
- }
- catch (SqlException ex)
- {
- if (myTrans.Connection != null)
- {
- Console.WriteLine("An exception of type " + ex.GetType() +
- " was encountered while attempting to roll back the transaction.");
- }
- }
-
- Console.WriteLine("An exception of type " + e.GetType() +
- " was encountered while inserting the data.");
- Console.WriteLine("Neither record was written to database.");
- }
- finally
- {
- myConnection.Close();
- }
- }
-
-
- Public Sub RunTransaction(myConnString As String)
- Dim myConnection As New MySqlConnection(myConnString)
- myConnection.Open()
-
- Dim myCommand As MySqlCommand = myConnection.CreateCommand()
- Dim myTrans As MySqlTransaction
-
- ' Start a local transaction
- myTrans = myConnection.BeginTransaction()
- ' Must assign both transaction object and connection
- ' to Command object for a pending local transaction
- myCommand.Connection = myConnection
- myCommand.Transaction = myTrans
-
- Try
- myCommand.CommandText = "Insert into Test (id, desc) VALUES (100, 'Description')"
- myCommand.ExecuteNonQuery()
- myCommand.CommandText = "Insert into Test (id, desc) VALUES (101, 'Description')"
- myCommand.ExecuteNonQuery()
- myTrans.Commit()
- Console.WriteLine("Both records are written to database.")
- Catch e As Exception
- Try
- myTrans.Rollback()
- Catch ex As MySqlException
- If Not myTrans.Connection Is Nothing Then
- Console.WriteLine("An exception of type " + ex.GetType().ToString() + _
- " was encountered while attempting to roll back the transaction.")
- End If
- End Try
-
- Console.WriteLine("An exception of type " + e.GetType().ToString() + _
- "was encountered while inserting the data.")
- Console.WriteLine("Neither record was written to database.")
- Finally
- myConnection.Close()
- End Try
- End Sub
-
-
- public void RunTransaction(string myConnString)
- {
- MySqlConnection myConnection = new MySqlConnection(myConnString);
- myConnection.Open();
-
- MySqlCommand myCommand = myConnection.CreateCommand();
- MySqlTransaction myTrans;
-
- // Start a local transaction
- myTrans = myConnection.BeginTransaction();
- // Must assign both transaction object and connection
- // to Command object for a pending local transaction
- myCommand.Connection = myConnection;
- myCommand.Transaction = myTrans;
-
- try
- {
- myCommand.CommandText = "insert into Test (id, desc) VALUES (100, 'Description')";
- myCommand.ExecuteNonQuery();
- myCommand.CommandText = "insert into Test (id, desc) VALUES (101, 'Description')";
- myCommand.ExecuteNonQuery();
- myTrans.Commit();
- Console.WriteLine("Both records are written to database.");
- }
- catch(Exception e)
- {
- try
- {
- myTrans.Rollback();
- }
- catch (SqlException ex)
- {
- if (myTrans.Connection != null)
- {
- Console.WriteLine("An exception of type " + ex.GetType() +
- " was encountered while attempting to roll back the transaction.");
- }
- }
-
- Console.WriteLine("An exception of type " + e.GetType() +
- " was encountered while inserting the data.");
- Console.WriteLine("Neither record was written to database.");
- }
- finally
- {
- myConnection.Close();
- }
- }
-
-
- Public Sub CreateMySqlConnection()
- Dim myConnString As String = _
- "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass"
- Dim myConnection As New MySqlConnection( myConnString )
- myConnection.Open()
- MessageBox.Show( "Server Version: " + myConnection.ServerVersion _
- + ControlChars.NewLine + "Database: " + myConnection.Database )
- myConnection.ChangeDatabase( "test2" )
- MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion _
- + ControlChars.NewLine + "Database: " + myConnection.Database )
- myConnection.Close()
- End Sub
-
-
-
- public void CreateMySqlConnection()
- {
- string myConnString =
- "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass";
- MySqlConnection myConnection = new MySqlConnection( myConnString );
- myConnection.Open();
- MessageBox.Show( "Server Version: " + myConnection.ServerVersion
- + "\nDatabase: " + myConnection.Database );
- myConnection.ChangeDatabase( "test2" );
- MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion
- + "\nDatabase: " + myConnection.Database );
- myConnection.Close();
- }
-
-
- Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
-
- Dim da As MySqlDataAdapter = New MySqlDataAdapter()
- Dim cmd As MySqlCommand
- Dim parm As MySqlParameter
-
- ' Create the SelectCommand.
- cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn)
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15)
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15)
-
- da.SelectCommand = cmd
-
- ' Create the DeleteCommand.
- cmd = New MySqlCommand("DELETE FROM mytable WHERE id=@id", conn)
-
- parm = cmd.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id")
- parm.SourceVersion = DataRowVersion.Original
-
- da.DeleteCommand = cmd
-
- Return da
- End Function
-
-
- public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
- {
- MySqlDataAdapter da = new MySqlDataAdapter();
- MySqlCommand cmd;
- MySqlParameter parm;
-
- // Create the SelectCommand.
- cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn);
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15);
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15);
-
- da.SelectCommand = cmd;
-
- // Create the DeleteCommand.
- cmd = new MySqlCommand("DELETE FROM mytable WHERE id=@id", conn);
-
- parm = cmd.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id");
- parm.SourceVersion = DataRowVersion.Original;
-
- da.DeleteCommand = cmd;
-
- return da;
- }
-
-
- Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
-
- Dim da As MySqlDataAdapter = New MySqlDataAdapter()
- Dim cmd As MySqlCommand
- Dim parm As MySqlParameter
-
- ' Create the SelectCommand.
- cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn)
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15)
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15)
-
- da.SelectCommand = cmd
-
- ' Create the InsertCommand.
- cmd = New MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id, @name)", conn)
-
- cmd.Parameters.Add( "@id", MySqlDbType.VarChar, 15, "id" )
- cmd.Parameters.Add( "@name", MySqlDbType.VarChar, 15, "name" )
- da.InsertCommand = cmd
-
- Return da
- End Function
-
-
- public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
- {
- MySqlDataAdapter da = new MySqlDataAdapter();
- MySqlCommand cmd;
- MySqlParameter parm;
-
- // Create the SelectCommand.
- cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn);
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15);
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15);
-
- da.SelectCommand = cmd;
-
- // Create the InsertCommand.
- cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id,@name)", conn);
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15, "id" );
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15, "name" );
-
- da.InsertCommand = cmd;
-
- return da;
- }
-
-
- Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
-
- Dim da As MySqlDataAdapter = New MySqlDataAdapter()
- Dim cmd As MySqlCommand
- Dim parm As MySqlParameter
-
- ' Create the SelectCommand.
- cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn)
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15)
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15)
-
- da.SelectCommand = cmd
-
- ' Create the InsertCommand.
- cmd = New MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id, @name)", conn)
-
- cmd.Parameters.Add( "@id", MySqlDbType.VarChar, 15, "id" )
- cmd.Parameters.Add( "@name", MySqlDbType.VarChar, 15, "name" )
- da.InsertCommand = cmd
-
- Return da
- End Function
-
-
- public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
- {
- MySqlDataAdapter da = new MySqlDataAdapter();
- MySqlCommand cmd;
- MySqlParameter parm;
-
- // Create the SelectCommand.
- cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn);
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15);
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15);
-
- da.SelectCommand = cmd;
-
- // Create the InsertCommand.
- cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id,@name)", conn);
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15, "id" );
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15, "name" );
-
- da.InsertCommand = cmd;
-
- return da;
- }
-
-
- Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter
-
- Dim da As MySqlDataAdapter = New MySqlDataAdapter()
- Dim cmd As MySqlCommand
- Dim parm As MySqlParameter
-
- ' Create the SelectCommand.
- cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn)
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15)
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15)
-
- da.SelectCommand = cmd
-
- ' Create the UpdateCommand.
- cmd = New MySqlCommand("UPDATE mytable SET id=@id, name=@name WHERE id=@oldId", conn)
-
- cmd.Parameters.Add( "@id", MySqlDbType.VarChar, 15, "id" )
- cmd.Parameters.Add( "@name", MySqlDbType.VarChar, 15, "name" )
-
- parm = cmd.Parameters.Add("@oldId", MySqlDbType.VarChar, 15, "id")
- parm.SourceVersion = DataRowVersion.Original
-
- da.UpdateCommand = cmd
-
- Return da
- End Function
-
-
- public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
- {
- MySqlDataAdapter da = new MySqlDataAdapter();
- MySqlCommand cmd;
- MySqlParameter parm;
-
- // Create the SelectCommand.
- cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn);
-
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15);
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15);
-
- da.SelectCommand = cmd;
-
- // Create the UpdateCommand.
- cmd = new MySqlCommand("UPDATE mytable SET id=@id, name=@name WHERE id=@oldId", conn);
- cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15, "id" );
- cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15, "name" );
-
- parm = cmd.Parameters.Add( "@oldId", MySqlDbType.VarChar, 15, "id" );
- parm.SourceVersion = DataRowVersion.Original;
-
- da.UpdateCommand = cmd;
-
- return da;
- }
-
-
- Public Sub ReadMyData(myConnString As String)
- Dim mySelectQuery As String = "SELECT OrderID, CustomerID FROM Orders"
- Dim myConnection As New MySqlConnection(myConnString)
- Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
- myConnection.Open()
- Dim myReader As MySqlDataReader
- myReader = myCommand.ExecuteReader()
- ' Always call Read before accessing data.
- While myReader.Read()
- Console.WriteLine((myReader.GetInt32(0) & ", " & myReader.GetString(1)))
- End While
- ' always call Close when done reading.
- myReader.Close()
- ' Close the connection when done with it.
- myConnection.Close()
- End Sub 'ReadMyData
-
-
- public void ReadMyData(string myConnString) {
- string mySelectQuery = "SELECT OrderID, CustomerID FROM Orders";
- MySqlConnection myConnection = new MySqlConnection(myConnString);
- MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection);
- myConnection.Open();
- MySqlDataReader myReader;
- myReader = myCommand.ExecuteReader();
- // Always call Read before accessing data.
- while (myReader.Read()) {
- Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));
- }
- // always call Close when done reading.
- myReader.Close();
- // Close the connection when done with it.
- myConnection.Close();
- }
-
-
- Public Sub ShowException()
- Dim mySelectQuery As String = "SELECT column1 FROM table1"
- Dim myConnection As New MySqlConnection ("Data Source=localhost;Database=Sample;")
- Dim myCommand As New MySqlCommand(mySelectQuery, myConnection)
-
- Try
- myCommand.Connection.Open()
- Catch e As MySqlException
- MessageBox.Show( e.Message )
- End Try
- End Sub
-
-
- public void ShowException()
- {
- string mySelectQuery = "SELECT column1 FROM table1";
- MySqlConnection myConnection =
- new MySqlConnection("Data Source=localhost;Database=Sample;");
- MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection);
-
- try
- {
- myCommand.Connection.Open();
- }
- catch (MySqlException e)
- {
- MessageBox.Show( e.Message );
- }
- }
-
-
- Public Sub AddParameters()
- ' ...
- ' create myDataSet and myDataAdapter
- ' ...
- myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters"
- myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239
-
- myDataAdapter.Fill(myDataSet)
- End Sub 'AddSqlParameters
-
-
- public void AddSqlParameters()
- {
- // ...
- // create myDataSet and myDataAdapter
- // ...
-
- myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters";
- myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239;
- myDataAdapter.Fill(myDataSet);
-
- }
-
-
- Public Sub RunTransaction(myConnString As String)
- Dim myConnection As New MySqlConnection(myConnString)
- myConnection.Open()
-
- Dim myCommand As MySqlCommand = myConnection.CreateCommand()
- Dim myTrans As MySqlTransaction
-
- ' Start a local transaction
- myTrans = myConnection.BeginTransaction()
- ' Must assign both transaction object and connection
- ' to Command object for a pending local transaction
- myCommand.Connection = myConnection
- myCommand.Transaction = myTrans
-
- Try
- myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
- myCommand.ExecuteNonQuery()
- myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
- myCommand.ExecuteNonQuery()
- myTrans.Commit()
- Console.WriteLine("Both records are written to database.")
- Catch e As Exception
- Try
- myTrans.Rollback()
- Catch ex As MySqlException
- If Not myTrans.Connection Is Nothing Then
- Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
- " was encountered while attempting to roll back the transaction.")
- End If
- End Try
-
- Console.WriteLine("An exception of type " & e.GetType().ToString() & _
- "was encountered while inserting the data.")
- Console.WriteLine("Neither record was written to database.")
- Finally
- myConnection.Close()
- End Try
- End Sub 'RunTransaction
-
-
- public void RunTransaction(string myConnString)
- {
- MySqlConnection myConnection = new MySqlConnection(myConnString);
- myConnection.Open();
-
- MySqlCommand myCommand = myConnection.CreateCommand();
- MySqlTransaction myTrans;
-
- // Start a local transaction
- myTrans = myConnection.BeginTransaction();
- // Must assign both transaction object and connection
- // to Command object for a pending local transaction
- myCommand.Connection = myConnection;
- myCommand.Transaction = myTrans;
-
- try
- {
- myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
- myCommand.ExecuteNonQuery();
- myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
- myCommand.ExecuteNonQuery();
- myTrans.Commit();
- Console.WriteLine("Both records are written to database.");
- }
- catch(Exception e)
- {
- try
- {
- myTrans.Rollback();
- }
- catch (MySqlException ex)
- {
- if (myTrans.Connection != null)
- {
- Console.WriteLine("An exception of type " + ex.GetType() +
- " was encountered while attempting to roll back the transaction.");
- }
- }
-
- Console.WriteLine("An exception of type " + e.GetType() +
- " was encountered while inserting the data.");
- Console.WriteLine("Neither record was written to database.");
- }
- finally
- {
- myConnection.Close();
- }
- }
-
-
- Public Sub RunSqlTransaction(myConnString As String)
- Dim myConnection As New MySqlConnection(myConnString)
- myConnection.Open()
-
- Dim myCommand As MySqlCommand = myConnection.CreateCommand()
- Dim myTrans As MySqlTransaction
-
- ' Start a local transaction
- myTrans = myConnection.BeginTransaction()
-
- ' Must assign both transaction object and connection
- ' to Command object for a pending local transaction
- myCommand.Connection = myConnection
- myCommand.Transaction = myTrans
-
- Try
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')"
- myCommand.ExecuteNonQuery()
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')"
- myCommand.ExecuteNonQuery()
- myTrans.Commit()
- Console.WriteLine("Success.")
- Catch e As Exception
- Try
- myTrans.Rollback()
- Catch ex As MySqlException
- If Not myTrans.Connection Is Nothing Then
- Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
- " was encountered while attempting to roll back the transaction.")
- End If
- End Try
-
- Console.WriteLine("An exception of type " & e.GetType().ToString() & _
- "was encountered while inserting the data.")
- Console.WriteLine("Neither record was written to database.")
- Finally
- myConnection.Close()
- End Try
- End Sub
-
-
- public void RunSqlTransaction(string myConnString)
- {
- MySqlConnection myConnection = new MySqlConnection(myConnString);
- myConnection.Open();
-
- MySqlCommand myCommand = myConnection.CreateCommand();
- MySqlTransaction myTrans;
-
- // Start a local transaction
- myTrans = myConnection.BeginTransaction();
- // Must assign both transaction object and connection
- // to Command object for a pending local transaction
- myCommand.Connection = myConnection;
- myCommand.Transaction = myTrans;
-
- try
- {
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')";
- myCommand.ExecuteNonQuery();
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')";
- myCommand.ExecuteNonQuery();
- myTrans.Commit();
- Console.WriteLine("Both records are written to database.");
- }
- catch(Exception e)
- {
- try
- {
- myTrans.Rollback();
- }
- catch (MySqlException ex)
- {
- if (myTrans.Connection != null)
- {
- Console.WriteLine("An exception of type " + ex.GetType() +
- " was encountered while attempting to roll back the transaction.");
- }
- }
-
- Console.WriteLine("An exception of type " + e.GetType() +
- " was encountered while inserting the data.");
- Console.WriteLine("Neither record was written to database.");
- }
- finally
- {
- myConnection.Close();
- }
- }
-
-
- Public Sub RunSqlTransaction(myConnString As String)
- Dim myConnection As New MySqlConnection(myConnString)
- myConnection.Open()
-
- Dim myCommand As MySqlCommand = myConnection.CreateCommand()
- Dim myTrans As MySqlTransaction
-
- ' Start a local transaction
- myTrans = myConnection.BeginTransaction()
-
- ' Must assign both transaction object and connection
- ' to Command object for a pending local transaction
- myCommand.Connection = myConnection
- myCommand.Transaction = myTrans
-
- Try
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')"
- myCommand.ExecuteNonQuery()
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')"
- myCommand.ExecuteNonQuery()
- myTrans.Commit()
- Console.WriteLine("Success.")
- Catch e As Exception
- Try
- myTrans.Rollback()
- Catch ex As MySqlException
- If Not myTrans.Connection Is Nothing Then
- Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
- " was encountered while attempting to roll back the transaction.")
- End If
- End Try
-
- Console.WriteLine("An exception of type " & e.GetType().ToString() & _
- "was encountered while inserting the data.")
- Console.WriteLine("Neither record was written to database.")
- Finally
- myConnection.Close()
- End Try
- End Sub
-
-
- public void RunSqlTransaction(string myConnString)
- {
- MySqlConnection myConnection = new MySqlConnection(myConnString);
- myConnection.Open();
-
- MySqlCommand myCommand = myConnection.CreateCommand();
- MySqlTransaction myTrans;
-
- // Start a local transaction
- myTrans = myConnection.BeginTransaction();
- // Must assign both transaction object and connection
- // to Command object for a pending local transaction
- myCommand.Connection = myConnection;
- myCommand.Transaction = myTrans;
-
- try
- {
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')";
- myCommand.ExecuteNonQuery();
- myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')";
- myCommand.ExecuteNonQuery();
- myTrans.Commit();
- Console.WriteLine("Both records are written to database.");
- }
- catch(Exception e)
- {
- try
- {
- myTrans.Rollback();
- }
- catch (MySqlException ex)
- {
- if (myTrans.Connection != null)
- {
- Console.WriteLine("An exception of type " + ex.GetType() +
- " was encountered while attempting to roll back the transaction.");
- }
- }
-
- Console.WriteLine("An exception of type " + e.GetType() +
- " was encountered while inserting the data.");
- Console.WriteLine("Neither record was written to database.");
- }
- finally
- {
- myConnection.Close();
- }
- }
-
-
- private void WriteEntry (String filename, Stream output)
- {
- DataSet ds1 = ObtainDataSet();
- ds1.WriteXml(output);
- }
-
- private void Run()
- {
- using (var zip = new ZipFile())
- {
- zip.AddEntry(zipEntryName, WriteEntry);
- zip.Save(zipFileName);
- }
- }
-
-
-
- Private Sub WriteEntry (ByVal filename As String, ByVal output As Stream)
- DataSet ds1 = ObtainDataSet()
- ds1.WriteXml(stream)
- End Sub
-
- Public Sub Run()
- Using zip = New ZipFile
- zip.AddEntry(zipEntryName, New WriteDelegate(AddressOf WriteEntry))
- zip.Save(zipFileName)
- End Using
- End Sub
-
-
- var cipher = new ZipCrypto();
- cipher.InitCipher(Password);
- // Decrypt the header. This has a side effect of "further initializing the
- // encryption keys" in the traditional zip encryption.
- byte[] DecryptedMessage = cipher.DecryptMessage(EncryptedMessage);
-
-
- Step 1 - Initializing the encryption keys
- -----------------------------------------
- Start with these keys:
- Key(0) := 305419896 (0x12345678)
- Key(1) := 591751049 (0x23456789)
- Key(2) := 878082192 (0x34567890)
-
- Then, initialize the keys with a password:
-
- loop for i from 0 to length(password)-1
- update_keys(password(i))
- end loop
-
- Where update_keys() is defined as:
-
- update_keys(char):
- Key(0) := crc32(key(0),char)
- Key(1) := Key(1) + (Key(0) bitwiseAND 000000ffH)
- Key(1) := Key(1) * 134775813 + 1
- Key(2) := crc32(key(2),key(1) rightshift 24)
- end update_keys
-
- Where crc32(old_crc,char) is a routine that given a CRC value and a
- character, returns an updated CRC value after applying the CRC-32
- algorithm described elsewhere in this document.
-
-
-
-
- using (ZipFile zip = new ZipFile(ZipFileToCreate))
- {
- ZipEntry e1= zip.AddFile(@"notes\Readme.txt");
- ZipEntry e2= zip.AddFile(@"music\StopThisTrain.mp3");
- e2.CompressionMethod = CompressionMethod.None;
- zip.Save();
- }
-
-
-
- Using zip As New ZipFile(ZipFileToCreate)
- zip.AddFile("notes\Readme.txt")
- Dim e2 as ZipEntry = zip.AddFile("music\StopThisTrain.mp3")
- e2.CompressionMethod = CompressionMethod.None
- zip.Save
- End Using
-
-
- // Create a zip archive with AES Encryption.
- using (ZipFile zip = new ZipFile())
- {
- zip.AddFile("ReadMe.txt")
- ZipEntry e1= zip.AddFile("2008-Regional-Sales-Report.pdf");
- e1.Encryption= EncryptionAlgorithm.WinZipAes256;
- e1.Password= "Top.Secret.No.Peeking!";
- zip.Save("EncryptedArchive.zip");
- }
-
- // Extract a zip archive that uses AES Encryption.
- // You do not need to specify the algorithm during extraction.
- using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
- {
- // Specify the password that is used during extraction, for
- // all entries that require a password:
- zip.Password= "Top.Secret.No.Peeking!";
- zip.ExtractAll("extractDirectory");
- }
-
-
-
- ' Create a zip that uses Encryption.
- Using zip As New ZipFile()
- zip.AddFile("ReadMe.txt")
- Dim e1 as ZipEntry
- e1= zip.AddFile("2008-Regional-Sales-Report.pdf")
- e1.Encryption= EncryptionAlgorithm.WinZipAes256
- e1.Password= "Top.Secret.No.Peeking!"
- zip.Save("EncryptedArchive.zip")
- End Using
-
- ' Extract a zip archive that uses AES Encryption.
- ' You do not need to specify the algorithm during extraction.
- Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
- ' Specify the password that is used during extraction, for
- ' all entries that require a password:
- zip.Password= "Top.Secret.No.Peeking!"
- zip.ExtractAll("extractDirectory")
- End Using
-
-
-
- // create a file with encryption
- using (ZipFile zip = new ZipFile())
- {
- ZipEntry entry;
- entry= zip.AddFile("Declaration.txt");
- entry.Password= "123456!";
- entry = zip.AddFile("Report.xls");
- entry.Password= "1Secret!";
- zip.Save("EncryptedArchive.zip");
- }
-
- // extract entries that use encryption
- using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
- {
- ZipEntry entry;
- entry = zip["Declaration.txt"];
- entry.Password = "123456!";
- entry.Extract("extractDir");
- entry = zip["Report.xls"];
- entry.Password = "1Secret!";
- entry.Extract("extractDir");
- }
-
-
-
-
- Using zip As New ZipFile
- Dim entry as ZipEntry
- entry= zip.AddFile("Declaration.txt")
- entry.Password= "123456!"
- entry = zip.AddFile("Report.xls")
- entry.Password= "1Secret!"
- zip.Save("EncryptedArchive.zip")
- End Using
-
-
- ' extract entries that use encryption
- Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
- Dim entry as ZipEntry
- entry = zip("Declaration.txt")
- entry.Password = "123456!"
- entry.Extract("extractDir")
- entry = zip("Report.xls")
- entry.Password = "1Secret!"
- entry.Extract("extractDir")
- End Using
-
-
-
-
- public static void ExtractProgress(object sender, ExtractProgressEventArgs e)
- {
- if (e.EventType == ZipProgressEventType.Extracting_BeforeExtractEntry)
- Console.WriteLine("extract {0} ", e.CurrentEntry.FileName);
-
- else if (e.EventType == ZipProgressEventType.Extracting_ExtractEntryWouldOverwrite)
- {
- ZipEntry entry = e.CurrentEntry;
- string response = null;
- // Ask the user if he wants overwrite the file
- do
- {
- Console.Write("Overwrite {0} in {1} ? (y/n/C) ", entry.FileName, e.ExtractLocation);
- response = Console.ReadLine();
- Console.WriteLine();
-
- } while (response != null && response[0]!='Y' &&
- response[0]!='N' && response[0]!='C');
-
- if (response[0]=='C')
- e.Cancel = true;
- else if (response[0]=='Y')
- entry.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
- else
- entry.ExtractExistingFile= ExtractExistingFileAction.DoNotOverwrite;
- }
- }
-
-
- using (var zip = new ZipFile())
- {
- zip.AlternateEnoding = System.Text.Encoding.GetEncoding("ibm861");
- zip.AlternateEnodingUsage = ZipOption.Always;
- zip.AddFileS(arrayOfFiles);
- zip.Save("Myarchive-Encoded-in-IBM861.zip");
- }
-
-
- using (var zip = new ZipFile())
- {
- var e = zip.UpdateFile("Descriptions.mme", "");
- e.IsText = true;
- zip.Save(zipPath);
- }
-
-
-
- Using zip As New ZipFile
- Dim e2 as ZipEntry = zip.AddFile("Descriptions.mme", "")
- e.IsText= True
- zip.Save(zipPath)
- End Using
-
-
- using (ZipFile zip = ZipFile.Read("PackedDocuments.zip"))
- {
- foreach (string s1 in zip.EntryFilenames)
- {
- if (s1.EndsWith(".txt"))
- {
- zip[s1].Extract("textfiles");
- }
- }
- }
-
-
- Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip")
- Dim s1 As String
- For Each s1 In zip.EntryFilenames
- If s1.EndsWith(".txt") Then
- zip(s1).Extract("textfiles")
- End If
- Next
- End Using
-
-
- String sZipPath = "Airborne.zip";
- String sFilePath = "Readme.txt";
- String sRootFolder = "Digado";
- using (ZipFile zip = ZipFile.Read(sZipPath))
- {
- if (zip.EntryFileNames.Contains(sFilePath))
- {
- // use the string indexer on the zip file
- zip[sFileName].Extract(sRootFolder,
- ExtractExistingFileAction.OverwriteSilently);
- }
- }
-
-
-
- Dim sZipPath as String = "Airborne.zip"
- Dim sFilePath As String = "Readme.txt"
- Dim sRootFolder As String = "Digado"
- Using zip As ZipFile = ZipFile.Read(sZipPath)
- If zip.EntryFileNames.Contains(sFilePath)
- ' use the string indexer on the zip file
- zip(sFilePath).Extract(sRootFolder, _
- ExtractExistingFileAction.OverwriteSilently)
- End If
- End Using
-
-
- using (var zip = ZipFile.Read(FilePath))
- {
- foreach (ZipEntry e in zip)
- {
- if (e.UsesEncryption)
- e.ExtractWithPassword("Secret!");
- else
- e.Extract();
- }
- }
-
-
- Using zip As ZipFile = ZipFile.Read(FilePath)
- Dim e As ZipEntry
- For Each e In zip
- If (e.UsesEncryption)
- e.ExtractWithPassword("Secret!")
- Else
- e.Extract
- End If
- Next
- End Using
-
-
- using (ZipFile zip = new ZipFile(ZipFileToRead))
- {
- ZipEntry e1= zip["Elevation.mp3"];
- using (Ionic.Zlib.CrcCalculatorStream s = e1.OpenReader())
- {
- byte[] buffer = new byte[4096];
- int n, totalBytesRead= 0;
- do {
- n = s.Read(buffer,0, buffer.Length);
- totalBytesRead+=n;
- } while (n>0);
- if (s.Crc32 != e1.Crc32)
- throw new Exception(string.Format("The Zip Entry failed the CRC Check. (0x{0:X8}!=0x{1:X8})", s.Crc32, e1.Crc32));
- if (totalBytesRead != e1.UncompressedSize)
- throw new Exception(string.Format("We read an unexpected number of bytes. ({0}!={1})", totalBytesRead, e1.UncompressedSize));
- }
- }
-
-
- Using zip As New ZipFile(ZipFileToRead)
- Dim e1 As ZipEntry = zip.Item("Elevation.mp3")
- Using s As Ionic.Zlib.CrcCalculatorStream = e1.OpenReader
- Dim n As Integer
- Dim buffer As Byte() = New Byte(4096) {}
- Dim totalBytesRead As Integer = 0
- Do
- n = s.Read(buffer, 0, buffer.Length)
- totalBytesRead = (totalBytesRead + n)
- Loop While (n > 0)
- If (s.Crc32 <> e1.Crc32) Then
- Throw New Exception(String.Format("The Zip Entry failed the CRC Check. (0x{0:X8}!=0x{1:X8})", s.Crc32, e1.Crc32))
- End If
- If (totalBytesRead <> e1.UncompressedSize) Then
- Throw New Exception(String.Format("We read an unexpected number of bytes. ({0}!={1})", totalBytesRead, e1.UncompressedSize))
- End If
- End Using
- End Using
-
-
- String[] itemnames= {
- "c:\\fixedContent\\Readme.txt",
- "MyProposal.docx",
- "c:\\SupportFiles", // a directory
- "images\\Image1.jpg"
- };
-
- try
- {
- using (ZipFile zip = new ZipFile())
- {
- for (int i = 1; i < itemnames.Length; i++)
- {
- // will add Files or Dirs, recurses and flattens subdirectories
- zip.AddItem(itemnames[i],"flat");
- }
- zip.Save(ZipToCreate);
- }
- }
- catch (System.Exception ex1)
- {
- System.Console.Error.WriteLine("exception: {0}", ex1);
- }
-
-
-
- Dim itemnames As String() = _
- New String() { "c:\fixedContent\Readme.txt", _
- "MyProposal.docx", _
- "SupportFiles", _
- "images\Image1.jpg" }
- Try
- Using zip As New ZipFile
- Dim i As Integer
- For i = 1 To itemnames.Length - 1
- ' will add Files or Dirs, recursing and flattening subdirectories.
- zip.AddItem(itemnames(i), "flat")
- Next i
- zip.Save(ZipToCreate)
- End Using
- Catch ex1 As Exception
- Console.Error.WriteLine("exception: {0}", ex1.ToString())
- End Try
-
-
- try
- {
- using (ZipFile zip = new ZipFile())
- {
- zip.AddFile("c:\\photos\\personal\\7440-N49th.png");
- zip.AddFile("c:\\Desktop\\2008-Regional-Sales-Report.pdf");
- zip.AddFile("ReadMe.txt");
-
- zip.Save("Package.zip");
- }
- }
- catch (System.Exception ex1)
- {
- System.Console.Error.WriteLine("exception: " + ex1);
- }
-
-
-
- Try
- Using zip As ZipFile = New ZipFile
- zip.AddFile("c:\photos\personal\7440-N49th.png")
- zip.AddFile("c:\Desktop\2008-Regional-Sales-Report.pdf")
- zip.AddFile("ReadMe.txt")
- zip.Save("Package.zip")
- End Using
- Catch ex1 As Exception
- Console.Error.WriteLine("exception: {0}", ex1.ToString)
- End Try
-
-
- try
- {
- using (ZipFile zip = new ZipFile())
- {
- // the following entry will be inserted at the root in the archive.
- zip.AddFile("c:\\datafiles\\ReadMe.txt", "");
- // this image file will be inserted into the "images" directory in the archive.
- zip.AddFile("c:\\photos\\personal\\7440-N49th.png", "images");
- // the following will result in a password-protected file called
- // files\\docs\\2008-Regional-Sales-Report.pdf in the archive.
- zip.Password = "EncryptMe!";
- zip.AddFile("c:\\Desktop\\2008-Regional-Sales-Report.pdf", "files\\docs");
- zip.Save("Archive.zip");
- }
- }
- catch (System.Exception ex1)
- {
- System.Console.Error.WriteLine("exception: {0}", ex1);
- }
-
-
-
- Try
- Using zip As ZipFile = New ZipFile
- ' the following entry will be inserted at the root in the archive.
- zip.AddFile("c:\datafiles\ReadMe.txt", "")
- ' this image file will be inserted into the "images" directory in the archive.
- zip.AddFile("c:\photos\personal\7440-N49th.png", "images")
- ' the following will result in a password-protected file called
- ' files\\docs\\2008-Regional-Sales-Report.pdf in the archive.
- zip.Password = "EncryptMe!"
- zip.AddFile("c:\Desktop\2008-Regional-Sales-Report.pdf", "files\documents")
- zip.Save("Archive.zip")
- End Using
- Catch ex1 As Exception
- Console.Error.WriteLine("exception: {0}", ex1)
- End Try
-
-
- String ZipFileToCreate = "archive1.zip";
- String DirectoryToZip = "c:\\reports";
- using (ZipFile zip = new ZipFile())
- {
- // Store all files found in the top level directory, into the zip archive.
- String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
- zip.AddFiles(filenames);
- zip.Save(ZipFileToCreate);
- }
-
-
-
- Dim ZipFileToCreate As String = "archive1.zip"
- Dim DirectoryToZip As String = "c:\reports"
- Using zip As ZipFile = New ZipFile
- ' Store all files found in the top level directory, into the zip archive.
- Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
- zip.AddFiles(filenames)
- zip.Save(ZipFileToCreate)
- End Using
-
-
- using (ZipFile zip1 = new ZipFile())
- {
- // UpdateFile might more accurately be called "AddOrUpdateFile"
- zip1.UpdateFile("MyDocuments\\Readme.txt");
- zip1.UpdateFile("CustomerList.csv");
- zip1.Comment = "This zip archive has been created.";
- zip1.Save("Content.zip");
- }
-
- using (ZipFile zip2 = ZipFile.Read("Content.zip"))
- {
- zip2.UpdateFile("Updates\\Readme.txt");
- zip2.Comment = "This zip archive has been updated: The Readme.txt file has been changed.";
- zip2.Save();
- }
-
-
-
- Using zip1 As New ZipFile
- ' UpdateFile might more accurately be called "AddOrUpdateFile"
- zip1.UpdateFile("MyDocuments\Readme.txt")
- zip1.UpdateFile("CustomerList.csv")
- zip1.Comment = "This zip archive has been created."
- zip1.Save("Content.zip")
- End Using
-
- Using zip2 As ZipFile = ZipFile.Read("Content.zip")
- zip2.UpdateFile("Updates\Readme.txt")
- zip2.Comment = "This zip archive has been updated: The Readme.txt file has been changed."
- zip2.Save
- End Using
-
-
- string Content = "This string will be the content of the Readme.txt file in the zip archive.";
- using (ZipFile zip1 = new ZipFile())
- {
- zip1.AddFile("MyDocuments\\Resume.doc", "files");
- zip1.AddEntry("Readme.txt", Content);
- zip1.Comment = "This zip file was created at " + System.DateTime.Now.ToString("G");
- zip1.Save("Content.zip");
- }
-
-
-
- Public Sub Run()
- Dim Content As String = "This string will be the content of the Readme.txt file in the zip archive."
- Using zip1 As ZipFile = New ZipFile
- zip1.AddEntry("Readme.txt", Content)
- zip1.AddFile("MyDocuments\Resume.doc", "files")
- zip1.Comment = ("This zip file was created at " & DateTime.Now.ToString("G"))
- zip1.Save("Content.zip")
- End Using
- End Sub
-
-
- 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.AddFile("Readme.txt");
- zip.Save(zipToCreate); // the stream is read implicitly here
- }
- }
-
-
-
- Dim zipToCreate As String = "Content.zip"
- Dim fileNameInArchive As String = "Content-From-Stream.bin"
- Using streamToRead as System.IO.Stream = MyStreamOpener()
- Using zip As ZipFile = New ZipFile()
- Dim entry as ZipEntry = zip.AddEntry(fileNameInArchive, streamToRead)
- zip.AddFile("Readme.txt")
- zip.Save(zipToCreate) '' the stream is read implicitly, here
- End Using
- End Using
-
-
- var c1= new System.Data.SqlClient.SqlConnection(connstring1);
- var da = new System.Data.SqlClient.SqlDataAdapter()
- {
- SelectCommand= new System.Data.SqlClient.SqlCommand(strSelect, c1)
- };
-
- DataSet ds1 = new DataSet();
- da.Fill(ds1, "Invoices");
-
- using(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
- {
- zip.AddEntry(zipEntryName, (name,stream) => ds1.WriteXml(stream) );
- zip.Save(zipFileName);
- }
-
-
- using (var input = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ))
- {
- using(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
- {
- zip.AddEntry(zipEntryName, (name,output) =>
- {
- byte[] buffer = new byte[BufferSize];
- int n;
- while ((n = input.Read(buffer, 0, buffer.Length)) != 0)
- {
- // could transform the data here...
- output.Write(buffer, 0, n);
- // could update a progress bar here
- }
- });
-
- zip.Save(zipFileName);
- }
- }
-
-
- Private Sub WriteEntry (ByVal name As String, ByVal output As Stream)
- Using input As FileStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
- Dim n As Integer = -1
- Dim buffer As Byte() = New Byte(BufferSize){}
- Do While n <> 0
- n = input.Read(buffer, 0, buffer.Length)
- output.Write(buffer, 0, n)
- Loop
- End Using
- End Sub
-
- Public Sub Run()
- Using zip = New ZipFile
- zip.AddEntry(zipEntryName, New WriteDelegate(AddressOf WriteEntry))
- zip.Save(zipFileName)
- End Using
- End Sub
-
-
- using(Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
- {
- zip.AddEntry(zipEntryName,
- (name) => File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ),
- (name, stream) => stream.Close()
- );
-
- zip.Save(zipFileName);
- }
-
-
-
-
- Function MyStreamOpener(ByVal entryName As String) As Stream
- '' This simply opens a file. You probably want to do somethinig
- '' more involved here: open a stream to read from a database,
- '' open a stream on an HTTP connection, and so on.
- Return File.OpenRead(entryName)
- End Function
-
- Sub MyStreamCloser(entryName As String, stream As Stream)
- stream.Close()
- End Sub
-
- Public Sub Run()
- Dim dirToZip As String = "fodder"
- Dim zipFileToCreate As String = "Archive.zip"
- Dim opener As OpenDelegate = AddressOf MyStreamOpener
- Dim closer As CloseDelegate = AddressOf MyStreamCloser
- Dim numFilestoAdd As Int32 = 4
- Using zip As ZipFile = New ZipFile
- Dim i As Integer
- For i = 0 To numFilesToAdd - 1
- zip.AddEntry(String.Format("content-{0:000}.txt"), opener, closer)
- Next i
- zip.Save(zipFileToCreate)
- End Using
- End Sub
-
-
-
- public void ZipUp(string targetZip, string directory)
- {
- using (var zip = new ZipFile())
- {
- zip.AddDirectory(directory, System.IO.Path.GetFileName(directory));
- zip.Save(targetZip);
- }
- }
-
-
- using (var zip = new ZipFile())
- {
- zip.FullScan = true;
- zip.Initialize(zipFileName);
- zip.Save(newName);
- }
-
-
-
- Using zip As New ZipFile
- zip.FullScan = True
- zip.Initialize(zipFileName)
- zip.Save(newName)
- End Using
-
-
- using (var zip = new ZipFile())
- {
- zip.AddFiles(filesToAdd);
- zip.SortEntriesBeforeSaving = true;
- zip.Save(name);
- }
-
-
-
- Using zip As New ZipFile
- zip.AddFiles(filesToAdd)
- zip.SortEntriesBeforeSaving = True
- zip.Save(name)
- End Using
-
-
- using (var zip = new ZipFile())
- {
- zip.AddDirectoryWillTraverseReparsePoints = false;
- zip.AddDirectory(dirToZip,"fodder");
- zip.Save(zipFileToCreate);
- }
-
-
- using (ZipFile zip = new ZipFile())
- {
- zip.SaveProgress += this.zip1_SaveProgress;
- zip.AddDirectory(directoryToZip, "");
- zip.UseZip64WhenSaving = Zip64Option.Always;
- zip.BufferSize = 65536*8; // 65536 * 8 = 512k
- zip.Save(ZipFileToCreate);
- }
-
-
- using (var zip = new ZipFile())
- {
- // produce a zip file the Mac will like
- zip.EmitTimesInWindowsFormatWhenSaving = false;
- zip.EmitTimesInUnixFormatWhenSaving = true;
- zip.AddDirectory(directoryToZip, "files");
- zip.Save(outputFile);
- }
-
-
-
- Using zip As New ZipFile
- '' produce a zip file the Mac will like
- zip.EmitTimesInWindowsFormatWhenSaving = False
- zip.EmitTimesInUnixFormatWhenSaving = True
- zip.AddDirectory(directoryToZip, "files")
- zip.Save(outputFile)
- End Using
-
-
- using (var zip = ZipFile.Read(zipFileName, System.Text.Encoding.GetEncoding("big5")))
- {
- // retrieve and extract an entry using a name encoded with CP950
- zip[MyDesiredEntry].Extract("unpack");
- }
-
-
-
- Using zip As ZipFile = ZipFile.Read(ZipToExtract, System.Text.Encoding.GetEncoding("big5"))
- ' retrieve and extract an entry using a name encoded with CP950
- zip(MyDesiredEntry).Extract("unpack")
- End Using
-
-
- using (ZipFile zip= ZipFile.Read(FilePath))
- {
- zip.StatusMessageTextWriter= System.Console.Out;
- // messages are sent to the console during extraction
- zip.ExtractAll();
- }
-
-
-
- Using zip As ZipFile = ZipFile.Read(FilePath)
- zip.StatusMessageTextWriter= System.Console.Out
- 'Status Messages will be sent to the console during extraction
- zip.ExtractAll()
- End Using
-
-
-
- var sw = new System.IO.StringWriter();
- using (ZipFile zip= ZipFile.Read(FilePath))
- {
- zip.StatusMessageTextWriter= sw;
- zip.ExtractAll();
- }
- Console.WriteLine("{0}", sw.ToString());
-
-
-
- Dim sw as New System.IO.StringWriter
- Using zip As ZipFile = ZipFile.Read(FilePath)
- zip.StatusMessageTextWriter= sw
- zip.ExtractAll()
- End Using
- 'Status Messages are now available in sw
-
-
-
- // create a file with encryption
- using (ZipFile zip = new ZipFile())
- {
- zip.AddFile("ReadMe.txt");
- zip.Password= "!Secret1";
- zip.AddFile("MapToTheSite-7440-N49th.png");
- zip.AddFile("2008-Regional-Sales-Report.pdf");
- zip.Save("EncryptedArchive.zip");
- }
-
- // extract entries that use encryption
- using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
- {
- zip.Password= "!Secret1";
- zip.ExtractAll("extractDir");
- }
-
-
-
-
- Using zip As New ZipFile
- zip.AddFile("ReadMe.txt")
- zip.Password = "123456!"
- zip.AddFile("MapToTheSite-7440-N49th.png")
- zip.Password= "!Secret1";
- zip.AddFile("2008-Regional-Sales-Report.pdf")
- zip.Save("EncryptedArchive.zip")
- End Using
-
-
- ' extract entries that use encryption
- Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
- zip.Password= "!Secret1"
- zip.ExtractAll("extractDir")
- End Using
-
-
-
-
- Public Sub SaveZipFile()
- Dim SourceFolder As String = "fodder"
- Dim DestFile As String = "eHandler.zip"
- Dim sw as New StringWriter
- Using zipArchive As ZipFile = New ZipFile
- ' Tell DotNetZip to skip any files for which it encounters an error
- zipArchive.ZipErrorAction = ZipErrorAction.Skip
- zipArchive.StatusMessageTextWriter = sw
- zipArchive.AddDirectory(SourceFolder)
- zipArchive.Save(DestFile)
- End Using
- ' examine sw here to see any messages
- End Sub
-
-
-
- // Create a zip archive with AES Encryption.
- using (ZipFile zip = new ZipFile())
- {
- zip.AddFile("ReadMe.txt");
- zip.Encryption= EncryptionAlgorithm.WinZipAes256;
- zip.Password= "Top.Secret.No.Peeking!";
- zip.AddFile("7440-N49th.png");
- zip.AddFile("2008-Regional-Sales-Report.pdf");
- zip.Save("EncryptedArchive.zip");
- }
-
- // Extract a zip archive that uses AES Encryption.
- // You do not need to specify the algorithm during extraction.
- using (ZipFile zip = ZipFile.Read("EncryptedArchive.zip"))
- {
- zip.Password= "Top.Secret.No.Peeking!";
- zip.ExtractAll("extractDirectory");
- }
-
-
-
- ' Create a zip that uses Encryption.
- Using zip As New ZipFile()
- zip.Encryption= EncryptionAlgorithm.WinZipAes256
- zip.Password= "Top.Secret.No.Peeking!"
- zip.AddFile("ReadMe.txt")
- zip.AddFile("7440-N49th.png")
- zip.AddFile("2008-Regional-Sales-Report.pdf")
- zip.Save("EncryptedArchive.zip")
- End Using
-
- ' Extract a zip archive that uses AES Encryption.
- ' You do not need to specify the algorithm during extraction.
- Using (zip as ZipFile = ZipFile.Read("EncryptedArchive.zip"))
- zip.Password= "Top.Secret.No.Peeking!"
- zip.ExtractAll("extractDirectory")
- End Using
-
-
-
- String ZipFileToCreate = "archive1.zip";
- String DirectoryToZip = "c:\\reports";
- using (ZipFile zip = new ZipFile())
- {
- // Store all files found in the top level directory, into the zip archive.
- String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
- zip.AddFiles(filenames, "files");
- zip.Save(ZipFileToCreate);
- }
-
-
-
- Dim ZipFileToCreate As String = "archive1.zip"
- Dim DirectoryToZip As String = "c:\reports"
- Using zip As ZipFile = New ZipFile()
- Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
- zip.AddFiles(filenames, "files")
- zip.Save(ZipFileToCreate)
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- // Store all files found in the top level directory, into the zip archive.
- // note: this code does not recurse subdirectories!
- String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
- zip.AddFiles(filenames, "files");
- zip.Save("Backup.zip");
- }
-
-
-
- Using zip As New ZipFile
- ' Store all files found in the top level directory, into the zip archive.
- ' note: this code does not recurse subdirectories!
- Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
- zip.AddFiles(filenames, "files")
- zip.Save("Backup.zip")
- End Using
-
-
- using (ZipFile zip = new ZipFile("Backup.zip", Console.Out))
- {
- // Store all files found in the top level directory, into the zip archive.
- // note: this code does not recurse subdirectories!
- // Status messages will be written to Console.Out
- String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
- zip.AddFiles(filenames);
- zip.Save();
- }
-
-
-
- Using zip As New ZipFile("Backup.zip", Console.Out)
- ' Store all files found in the top level directory, into the zip archive.
- ' note: this code does not recurse subdirectories!
- ' Status messages will be written to Console.Out
- Dim filenames As String() = System.IO.Directory.GetFiles(DirectoryToZip)
- zip.AddFiles(filenames)
- zip.Save()
- End Using
-
-
- using (ZipFile zip = ZipFile.Read("PackedDocuments.zip"))
- {
- foreach (string s1 in zip.EntryFilenames)
- {
- if (s1.EndsWith(".txt"))
- zip[s1].Extract("textfiles");
- }
- }
-
-
- Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip")
- Dim s1 As String
- For Each s1 In zip.EntryFilenames
- If s1.EndsWith(".txt") Then
- zip(s1).Extract("textfiles")
- End If
- Next
- End Using
-
-
- String zipFileToRead= "PackedDocuments.zip";
- string candidate = "DatedMaterial.xps";
- using (ZipFile zip = new ZipFile(zipFileToRead))
- {
- if (zip.EntryFilenames.Contains(candidate))
- Console.WriteLine("The file '{0}' exists in the zip archive '{1}'",
- candidate,
- zipFileName);
- else
- Console.WriteLine("The file, '{0}', does not exist in the zip archive '{1}'",
- candidate,
- zipFileName);
- Console.WriteLine();
- }
-
-
- Dim zipFileToRead As String = "PackedDocuments.zip"
- Dim candidate As String = "DatedMaterial.xps"
- Using zip As ZipFile.Read(ZipFileToRead)
- If zip.EntryFilenames.Contains(candidate) Then
- Console.WriteLine("The file '{0}' exists in the zip archive '{1}'", _
- candidate, _
- zipFileName)
- Else
- Console.WriteLine("The file, '{0}', does not exist in the zip archive '{1}'", _
- candidate, _
- zipFileName)
- End If
- Console.WriteLine
- End Using
-
-
- using (ZipFile zip = ZipFile.Read(zipFile))
- {
- foreach (ZipEntry entry in zip.EntriesSorted)
- {
- ListViewItem item = new ListViewItem(n.ToString());
- n++;
- string[] subitems = new string[] {
- entry.FileName.Replace("/","\\"),
- entry.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
- entry.UncompressedSize.ToString(),
- String.Format("{0,5:F0}%", entry.CompressionRatio),
- entry.CompressedSize.ToString(),
- (entry.UsesEncryption) ? "Y" : "N",
- String.Format("{0:X8}", entry.Crc)};
-
- foreach (String s in subitems)
- {
- ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem();
- subitem.Text = s;
- item.SubItems.Add(subitem);
- }
-
- this.listView1.Items.Add(item);
- }
- }
-
-
- String ZipFileToRead = "ArchiveToModify.zip";
- System.DateTime Threshold = new System.DateTime(2007,12,31);
- using (ZipFile zip = ZipFile.Read(ZipFileToRead))
- {
- var EntriesToRemove = new System.Collections.Generic.List<ZipEntry>();
- foreach (ZipEntry e in zip)
- {
- if (e.LastModified < Threshold)
- {
- // We cannot remove the entry from the list, within the context of
- // an enumeration of said list.
- // So we add the doomed entry to a list to be removed later.
- EntriesToRemove.Add(e);
- }
- }
-
- // actually remove the doomed entries.
- foreach (ZipEntry zombie in EntriesToRemove)
- zip.RemoveEntry(zombie);
-
- zip.Comment= String.Format("This zip archive was updated at {0}.",
- System.DateTime.Now.ToString("G"));
-
- // save with a different name
- zip.Save("Archive-Updated.zip");
- }
-
-
-
- Dim ZipFileToRead As String = "ArchiveToModify.zip"
- Dim Threshold As New DateTime(2007, 12, 31)
- Using zip As ZipFile = ZipFile.Read(ZipFileToRead)
- Dim EntriesToRemove As New System.Collections.Generic.List(Of ZipEntry)
- Dim e As ZipEntry
- For Each e In zip
- If (e.LastModified < Threshold) Then
- ' We cannot remove the entry from the list, within the context of
- ' an enumeration of said list.
- ' So we add the doomed entry to a list to be removed later.
- EntriesToRemove.Add(e)
- End If
- Next
-
- ' actually remove the doomed entries.
- Dim zombie As ZipEntry
- For Each zombie In EntriesToRemove
- zip.RemoveEntry(zombie)
- Next
- zip.Comment = String.Format("This zip archive was updated at {0}.", DateTime.Now.ToString("G"))
- 'save as a different name
- zip.Save("Archive-Updated.zip")
- End Using
-
-
- String zipFileToRead= "PackedDocuments.zip";
- string candidate = "DatedMaterial.xps";
- using (ZipFile zip = ZipFile.Read(zipFileToRead))
- {
- if (zip.EntryFilenames.Contains(candidate))
- {
- zip.RemoveEntry(candidate);
- zip.Comment= String.Format("The file '{0}' has been removed from this archive.",
- Candidate);
- zip.Save();
- }
- }
-
-
- Dim zipFileToRead As String = "PackedDocuments.zip"
- Dim candidate As String = "DatedMaterial.xps"
- Using zip As ZipFile = ZipFile.Read(zipFileToRead)
- If zip.EntryFilenames.Contains(candidate) Then
- zip.RemoveEntry(candidate)
- zip.Comment = String.Format("The file '{0}' has been removed from this archive.", Candidate)
- zip.Save
- End If
- End Using
-
-
- using (ZipFile zip = ZipFile.Read(zipfile))
- {
- foreach (ZipEntry e in zip)
- {
- if (WantThisEntry(e.FileName))
- zip.Extract(e.FileName, Console.OpenStandardOutput());
- }
- } // Dispose() is called implicitly here.
-
-
-
- Using zip As ZipFile = ZipFile.Read(zipfile)
- Dim e As ZipEntry
- For Each e In zip
- If WantThisEntry(e.FileName) Then
- zip.Extract(e.FileName, Console.OpenStandardOutput())
- End If
- Next
- End Using ' Dispose is implicity called here
-
-
- progressBar1.Value = 0;
- progressBar1.Max = listbox1.Items.Count;
- using (ZipFile zip = new ZipFile())
- {
- // listbox1 contains a list of filenames
- zip.AddFiles(listbox1.Items);
-
- // do the progress bar:
- zip.SaveProgress += (sender, e) => {
- if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry) {
- progressBar1.PerformStep();
- }
- };
-
- zip.Save(fs);
- }
-
-
- static bool justHadByteUpdate= false;
- public static void SaveProgress(object sender, SaveProgressEventArgs e)
- {
- if (e.EventType == ZipProgressEventType.Saving_Started)
- Console.WriteLine("Saving: {0}", e.ArchiveName);
-
- else if (e.EventType == ZipProgressEventType.Saving_Completed)
- {
- justHadByteUpdate= false;
- Console.WriteLine();
- Console.WriteLine("Done: {0}", e.ArchiveName);
- }
-
- else if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
- {
- if (justHadByteUpdate)
- Console.WriteLine();
- Console.WriteLine(" Writing: {0} ({1}/{2})",
- e.CurrentEntry.FileName, e.EntriesSaved, e.EntriesTotal);
- justHadByteUpdate= false;
- }
-
- else if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead)
- {
- if (justHadByteUpdate)
- Console.SetCursorPosition(0, Console.CursorTop);
- Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer,
- e.BytesTransferred / (0.01 * e.TotalBytesToTransfer ));
- justHadByteUpdate= true;
- }
- }
-
- public static ZipUp(string targetZip, string directory)
- {
- using (var zip = new ZipFile()) {
- zip.SaveProgress += SaveProgress;
- zip.AddDirectory(directory);
- zip.Save(targetZip);
- }
- }
-
-
-
-
- Public Sub ZipUp(ByVal targetZip As String, ByVal directory As String)
- Using zip As ZipFile = New ZipFile
- AddHandler zip.SaveProgress, AddressOf MySaveProgress
- zip.AddDirectory(directory)
- zip.Save(targetZip)
- End Using
- End Sub
-
- Private Shared justHadByteUpdate As Boolean = False
-
- Public Shared Sub MySaveProgress(ByVal sender As Object, ByVal e As SaveProgressEventArgs)
- If (e.EventType Is ZipProgressEventType.Saving_Started) Then
- Console.WriteLine("Saving: {0}", e.ArchiveName)
-
- ElseIf (e.EventType Is ZipProgressEventType.Saving_Completed) Then
- justHadByteUpdate = False
- Console.WriteLine
- Console.WriteLine("Done: {0}", e.ArchiveName)
-
- ElseIf (e.EventType Is ZipProgressEventType.Saving_BeforeWriteEntry) Then
- If justHadByteUpdate Then
- Console.WriteLine
- End If
- Console.WriteLine(" Writing: {0} ({1}/{2})", e.CurrentEntry.FileName, e.EntriesSaved, e.EntriesTotal)
- justHadByteUpdate = False
-
- ElseIf (e.EventType Is ZipProgressEventType.Saving_EntryBytesRead) Then
- If justHadByteUpdate Then
- Console.SetCursorPosition(0, Console.CursorTop)
- End If
- Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, _
- e.TotalBytesToTransfer, _
- (CDbl(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer)))
- justHadByteUpdate = True
- End If
- End Sub
-
-
- delegate void SaveEntryProgress(SaveProgressEventArgs e);
- delegate void ButtonClick(object sender, EventArgs e);
-
- public class WorkerOptions
- {
- public string ZipName;
- public string Folder;
- public string Encoding;
- public string Comment;
- public int ZipFlavor;
- public Zip64Option Zip64;
- }
-
- private int _progress2MaxFactor;
- private bool _saveCanceled;
- private long _totalBytesBeforeCompress;
- private long _totalBytesAfterCompress;
- private Thread _workerThread;
-
-
- private void btnZipup_Click(object sender, EventArgs e)
- {
- KickoffZipup();
- }
-
- private void btnCancel_Click(object sender, EventArgs e)
- {
- if (this.lblStatus.InvokeRequired)
- {
- this.lblStatus.Invoke(new ButtonClick(this.btnCancel_Click), new object[] { sender, e });
- }
- else
- {
- _saveCanceled = true;
- lblStatus.Text = "Canceled...";
- ResetState();
- }
- }
-
- private void KickoffZipup()
- {
- _folderName = tbDirName.Text;
-
- if (_folderName == null || _folderName == "") return;
- if (this.tbZipName.Text == null || this.tbZipName.Text == "") return;
-
- // check for existence of the zip file:
- if (System.IO.File.Exists(this.tbZipName.Text))
- {
- var dlgResult = MessageBox.Show(String.Format("The file you have specified ({0}) already exists." +
- " Do you want to overwrite this file?", this.tbZipName.Text),
- "Confirmation is Required", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
- if (dlgResult != DialogResult.Yes) return;
- System.IO.File.Delete(this.tbZipName.Text);
- }
-
- _saveCanceled = false;
- _nFilesCompleted = 0;
- _totalBytesAfterCompress = 0;
- _totalBytesBeforeCompress = 0;
- this.btnOk.Enabled = false;
- this.btnOk.Text = "Zipping...";
- this.btnCancel.Enabled = true;
- lblStatus.Text = "Zipping...";
-
- var options = new WorkerOptions
- {
- ZipName = this.tbZipName.Text,
- Folder = _folderName,
- Encoding = "ibm437"
- };
-
- if (this.comboBox1.SelectedIndex != 0)
- {
- options.Encoding = this.comboBox1.SelectedItem.ToString();
- }
-
- if (this.radioFlavorSfxCmd.Checked)
- options.ZipFlavor = 2;
- else if (this.radioFlavorSfxGui.Checked)
- options.ZipFlavor = 1;
- else options.ZipFlavor = 0;
-
- if (this.radioZip64AsNecessary.Checked)
- options.Zip64 = Zip64Option.AsNecessary;
- else if (this.radioZip64Always.Checked)
- options.Zip64 = Zip64Option.Always;
- else options.Zip64 = Zip64Option.Never;
-
- options.Comment = String.Format("Encoding:{0} || Flavor:{1} || ZIP64:{2}\r\nCreated at {3} || {4}\r\n",
- options.Encoding,
- FlavorToString(options.ZipFlavor),
- options.Zip64.ToString(),
- System.DateTime.Now.ToString("yyyy-MMM-dd HH:mm:ss"),
- this.Text);
-
- if (this.tbComment.Text != TB_COMMENT_NOTE)
- options.Comment += this.tbComment.Text;
-
- _workerThread = new Thread(this.DoSave);
- _workerThread.Name = "Zip Saver thread";
- _workerThread.Start(options);
- this.Cursor = Cursors.WaitCursor;
- }
-
-
- private void DoSave(Object p)
- {
- WorkerOptions options = p as WorkerOptions;
- try
- {
- using (var zip1 = new ZipFile())
- {
- zip1.ProvisionalAlternateEncoding = System.Text.Encoding.GetEncoding(options.Encoding);
- zip1.Comment = options.Comment;
- zip1.AddDirectory(options.Folder);
- _entriesToZip = zip1.EntryFileNames.Count;
- SetProgressBars();
- zip1.SaveProgress += this.zip1_SaveProgress;
-
- zip1.UseZip64WhenSaving = options.Zip64;
-
- if (options.ZipFlavor == 1)
- zip1.SaveSelfExtractor(options.ZipName, SelfExtractorFlavor.WinFormsApplication);
- else if (options.ZipFlavor == 2)
- zip1.SaveSelfExtractor(options.ZipName, SelfExtractorFlavor.ConsoleApplication);
- else
- zip1.Save(options.ZipName);
- }
- }
- catch (System.Exception exc1)
- {
- MessageBox.Show(String.Format("Exception while zipping: {0}", exc1.Message));
- btnCancel_Click(null, null);
- }
- }
-
-
-
- void zip1_SaveProgress(object sender, SaveProgressEventArgs e)
- {
- switch (e.EventType)
- {
- case ZipProgressEventType.Saving_AfterWriteEntry:
- StepArchiveProgress(e);
- break;
- case ZipProgressEventType.Saving_EntryBytesRead:
- StepEntryProgress(e);
- break;
- case ZipProgressEventType.Saving_Completed:
- SaveCompleted();
- break;
- case ZipProgressEventType.Saving_AfterSaveTempArchive:
- // this event only occurs when saving an SFX file
- TempArchiveSaved();
- break;
- }
- if (_saveCanceled)
- e.Cancel = true;
- }
-
-
-
- private void StepArchiveProgress(SaveProgressEventArgs e)
- {
- if (this.progressBar1.InvokeRequired)
- {
- this.progressBar1.Invoke(new SaveEntryProgress(this.StepArchiveProgress), new object[] { e });
- }
- else
- {
- if (!_saveCanceled)
- {
- _nFilesCompleted++;
- this.progressBar1.PerformStep();
- _totalBytesAfterCompress += e.CurrentEntry.CompressedSize;
- _totalBytesBeforeCompress += e.CurrentEntry.UncompressedSize;
-
- // reset the progress bar for the entry:
- this.progressBar2.Value = this.progressBar2.Maximum = 1;
-
- this.Update();
- }
- }
- }
-
-
- private void StepEntryProgress(SaveProgressEventArgs e)
- {
- if (this.progressBar2.InvokeRequired)
- {
- this.progressBar2.Invoke(new SaveEntryProgress(this.StepEntryProgress), new object[] { e });
- }
- else
- {
- if (!_saveCanceled)
- {
- if (this.progressBar2.Maximum == 1)
- {
- // reset
- Int64 max = e.TotalBytesToTransfer;
- _progress2MaxFactor = 0;
- while (max > System.Int32.MaxValue)
- {
- max /= 2;
- _progress2MaxFactor++;
- }
- this.progressBar2.Maximum = (int)max;
- lblStatus.Text = String.Format("{0} of {1} files...({2})",
- _nFilesCompleted + 1, _entriesToZip, e.CurrentEntry.FileName);
- }
-
- int xferred = e.BytesTransferred >> _progress2MaxFactor;
-
- this.progressBar2.Value = (xferred >= this.progressBar2.Maximum)
- ? this.progressBar2.Maximum
- : xferred;
-
- this.Update();
- }
- }
- }
-
- private void SaveCompleted()
- {
- if (this.lblStatus.InvokeRequired)
- {
- this.lblStatus.Invoke(new MethodInvoker(this.SaveCompleted));
- }
- else
- {
- lblStatus.Text = String.Format("Done, Compressed {0} files, {1:N0}% of original.",
- _nFilesCompleted, (100.00 * _totalBytesAfterCompress) / _totalBytesBeforeCompress);
- ResetState();
- }
- }
-
- private void ResetState()
- {
- this.btnCancel.Enabled = false;
- this.btnOk.Enabled = true;
- this.btnOk.Text = "Zip it!";
- this.progressBar1.Value = 0;
- this.progressBar2.Value = 0;
- this.Cursor = Cursors.Default;
- if (!_workerThread.IsAlive)
- _workerThread.Join();
- }
-
-
-
- private static bool justHadByteUpdate = false;
- public static void ExtractProgress(object sender, ExtractProgressEventArgs e)
- {
- if(e.EventType == ZipProgressEventType.Extracting_EntryBytesWritten)
- {
- if (justHadByteUpdate)
- Console.SetCursorPosition(0, Console.CursorTop);
-
- Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer,
- e.BytesTransferred / (0.01 * e.TotalBytesToTransfer ));
- justHadByteUpdate = true;
- }
- else if(e.EventType == ZipProgressEventType.Extracting_BeforeExtractEntry)
- {
- if (justHadByteUpdate)
- Console.WriteLine();
- Console.WriteLine("Extracting: {0}", e.CurrentEntry.FileName);
- justHadByteUpdate= false;
- }
- }
-
- public static ExtractZip(string zipToExtract, string directory)
- {
- string TargetDirectory= "extract";
- using (var zip = ZipFile.Read(zipToExtract)) {
- zip.ExtractProgress += ExtractProgress;
- foreach (var e in zip1)
- {
- e.Extract(TargetDirectory, true);
- }
- }
- }
-
-
-
- Public Shared Sub Main(ByVal args As String())
- Dim ZipToUnpack As String = "C1P3SML.zip"
- Dim TargetDir As String = "ExtractTest_Extract"
- Console.WriteLine("Extracting file {0} to {1}", ZipToUnpack, TargetDir)
- Using zip1 As ZipFile = ZipFile.Read(ZipToUnpack)
- AddHandler zip1.ExtractProgress, AddressOf MyExtractProgress
- Dim e As ZipEntry
- For Each e In zip1
- e.Extract(TargetDir, True)
- Next
- End Using
- End Sub
-
- Private Shared justHadByteUpdate As Boolean = False
-
- Public Shared Sub MyExtractProgress(ByVal sender As Object, ByVal e As ExtractProgressEventArgs)
- If (e.EventType = ZipProgressEventType.Extracting_EntryBytesWritten) Then
- If ExtractTest.justHadByteUpdate Then
- Console.SetCursorPosition(0, Console.CursorTop)
- End If
- Console.Write(" {0}/{1} ({2:N0}%)", e.BytesTransferred, e.TotalBytesToTransfer, (CDbl(e.BytesTransferred) / (0.01 * e.TotalBytesToTransfer)))
- ExtractTest.justHadByteUpdate = True
- ElseIf (e.EventType = ZipProgressEventType.Extracting_BeforeExtractEntry) Then
- If ExtractTest.justHadByteUpdate Then
- Console.WriteLine
- End If
- Console.WriteLine("Extracting: {0}", e.CurrentEntry.FileName)
- ExtractTest.justHadByteUpdate = False
- End If
- End Sub
-
-
-
- int _numEntriesToAdd= 0;
- int _numEntriesAdded= 0;
- void AddProgressHandler(object sender, AddProgressEventArgs e)
- {
- switch (e.EventType)
- {
- case ZipProgressEventType.Adding_Started:
- Console.WriteLine("Adding files to the zip...");
- break;
- case ZipProgressEventType.Adding_AfterAddEntry:
- _numEntriesAdded++;
- Console.WriteLine(String.Format("Adding file {0}/{1} :: {2}",
- _numEntriesAdded, _numEntriesToAdd, e.CurrentEntry.FileName));
- break;
- case ZipProgressEventType.Adding_Completed:
- Console.WriteLine("Added all files");
- break;
- }
- }
-
- void CreateTheZip()
- {
- using (ZipFile zip = new ZipFile())
- {
- zip.AddProgress += AddProgressHandler;
- zip.AddDirectory(System.IO.Path.GetFileName(DirToZip));
- zip.Save(ZipFileToCreate);
- }
- }
-
-
-
-
-
- Private Sub AddProgressHandler(ByVal sender As Object, ByVal e As AddProgressEventArgs)
- Select Case e.EventType
- Case ZipProgressEventType.Adding_Started
- Console.WriteLine("Adding files to the zip...")
- Exit Select
- Case ZipProgressEventType.Adding_AfterAddEntry
- Console.WriteLine(String.Format("Adding file {0}", e.CurrentEntry.FileName))
- Exit Select
- Case ZipProgressEventType.Adding_Completed
- Console.WriteLine("Added all files")
- Exit Select
- End Select
- End Sub
-
- Sub CreateTheZip()
- Using zip as ZipFile = New ZipFile
- AddHandler zip.AddProgress, AddressOf AddProgressHandler
- zip.AddDirectory(System.IO.Path.GetFileName(DirToZip))
- zip.Save(ZipFileToCreate);
- End Using
- End Sub
-
-
-
-
-
- public static void MyZipError(object sender, ZipErrorEventArgs e)
- {
- Console.WriteLine("Error saving {0}...", e.FileName);
- Console.WriteLine(" Exception: {0}", e.exception);
- ZipEntry entry = e.CurrentEntry;
- string response = null;
- // Ask the user whether he wants to skip this error or not
- do
- {
- Console.Write("Retry, Skip, Throw, or Cancel ? (R/S/T/C) ");
- response = Console.ReadLine();
- Console.WriteLine();
-
- } while (response != null &&
- response[0]!='S' && response[0]!='s' &&
- response[0]!='R' && response[0]!='r' &&
- response[0]!='T' && response[0]!='t' &&
- response[0]!='C' && response[0]!='c');
-
- e.Cancel = (response[0]=='C' || response[0]=='c');
-
- if (response[0]=='S' || response[0]=='s')
- entry.ZipErrorAction = ZipErrorAction.Skip;
- else if (response[0]=='R' || response[0]=='r')
- entry.ZipErrorAction = ZipErrorAction.Retry;
- else if (response[0]=='T' || response[0]=='t')
- entry.ZipErrorAction = ZipErrorAction.Throw;
- }
-
- public void SaveTheFile()
- {
- string directoryToZip = "fodder";
- string directoryInArchive = "files";
- string zipFileToCreate = "Archive.zip";
- using (var zip = new ZipFile())
- {
- // set the event handler before adding any entries
- zip.ZipError += MyZipError;
- zip.AddDirectory(directoryToZip, directoryInArchive);
- zip.Save(zipFileToCreate);
- }
- }
-
-
-
- Private Sub MyZipError(ByVal sender As Object, ByVal e As Ionic.Zip.ZipErrorEventArgs)
- ' At this point, the application could prompt the user for an action to take.
- ' But in this case, this application will simply automatically skip the file, in case of error.
- Console.WriteLine("Zip Error, entry {0}", e.CurrentEntry.FileName)
- Console.WriteLine(" Exception: {0}", e.exception)
- ' set the desired ZipErrorAction on the CurrentEntry to communicate that to DotNetZip
- e.CurrentEntry.ZipErrorAction = Zip.ZipErrorAction.Skip
- End Sub
-
- Public Sub SaveTheFile()
- Dim directoryToZip As String = "fodder"
- Dim directoryInArchive As String = "files"
- Dim zipFileToCreate as String = "Archive.zip"
- Using zipArchive As ZipFile = New ZipFile
- ' set the event handler before adding any entries
- AddHandler zipArchive.ZipError, AddressOf MyZipError
- zipArchive.AddDirectory(directoryToZip, directoryInArchive)
- zipArchive.Save(zipFileToCreate)
- End Using
- End Sub
-
-
-
- String TargetDirectory= "unpack";
- using(ZipFile zip= ZipFile.Read(ZipFileToExtract))
- {
- zip.ExtractExistingFile= ExtractExistingFileAction.OverwriteSilently;
- zip.ExtractAll(TargetDirectory);
- }
-
-
-
- Dim TargetDirectory As String = "unpack"
- Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
- zip.ExtractExistingFile= ExtractExistingFileAction.OverwriteSilently
- zip.ExtractAll(TargetDirectory)
- End Using
-
-
- String TargetDirectory= "c:\\unpack";
- using(ZipFile zip= ZipFile.Read(ZipFileToExtract))
- {
- zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.DontOverwrite);
- }
-
-
-
- Dim TargetDirectory As String = "c:\unpack"
- Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
- zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.DontOverwrite)
- End Using
-
-
- string zipToExtract = "MyArchive.zip";
- string extractDirectory = "extract";
- var options = new ReadOptions
- {
- StatusMessageWriter = System.Console.Out,
- Encoding = System.Text.Encoding.GetEncoding(950)
- };
- using (ZipFile zip = ZipFile.Read(zipToExtract, options))
- {
- foreach (ZipEntry e in zip)
- {
- e.Extract(extractDirectory);
- }
- }
-
-
-
-
- Dim zipToExtract as String = "MyArchive.zip"
- Dim extractDirectory as String = "extract"
- Dim options as New ReadOptions
- options.Encoding = System.Text.Encoding.GetEncoding(950)
- options.StatusMessageWriter = System.Console.Out
- Using zip As ZipFile = ZipFile.Read(zipToExtract, options)
- Dim e As ZipEntry
- For Each e In zip
- e.Extract(extractDirectory)
- Next
- End Using
-
-
- var options = new ReadOptions
- {
- StatusMessageWriter = new System.IO.StringWriter()
- };
- using (ZipFile zip = ZipFile.Read("PackedDocuments.zip", options))
- {
- var Threshold = new DateTime(2007,7,4);
- // We cannot remove the entry from the list, within the context of
- // an enumeration of said list.
- // So we add the doomed entry to a list to be removed later.
- // pass 1: mark the entries for removal
- var MarkedEntries = new System.Collections.Generic.List<ZipEntry>();
- foreach (ZipEntry e in zip)
- {
- if (e.LastModified < Threshold)
- MarkedEntries.Add(e);
- }
- // pass 2: actually remove the entry.
- foreach (ZipEntry zombie in MarkedEntries)
- zip.RemoveEntry(zombie);
- zip.Comment = "This archive has been updated.";
- zip.Save();
- }
- // can now use contents of sw, eg store in an audit log
-
-
-
- Dim options as New ReadOptions
- options.StatusMessageWriter = New System.IO.StringWriter
- Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip", options)
- Dim Threshold As New DateTime(2007, 7, 4)
- ' We cannot remove the entry from the list, within the context of
- ' an enumeration of said list.
- ' So we add the doomed entry to a list to be removed later.
- ' pass 1: mark the entries for removal
- Dim MarkedEntries As New System.Collections.Generic.List(Of ZipEntry)
- Dim e As ZipEntry
- For Each e In zip
- If (e.LastModified < Threshold) Then
- MarkedEntries.Add(e)
- End If
- Next
- ' pass 2: actually remove the entry.
- Dim zombie As ZipEntry
- For Each zombie In MarkedEntries
- zip.RemoveEntry(zombie)
- Next
- zip.Comment = "This archive has been updated."
- zip.Save
- End Using
- ' can now use contents of sw, eg store in an audit log
-
-
- using (ZipFile zip = ZipFile.Read(InputStream))
- {
- zip.Extract("NameOfEntryInArchive.doc", OutputStream);
- }
-
-
-
- Using zip as ZipFile = ZipFile.Read(InputStream)
- zip.Extract("NameOfEntryInArchive.doc", OutputStream)
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- zip.AddDirectory(@"c:\reports\January");
- zip.Save("January.zip");
- }
-
-
-
- Using zip As New ZipFile()
- zip.AddDirectory("c:\reports\January")
- zip.Save("January.zip")
- End Using
-
-
-
- using (ZipFile zip = ZipFile.Read("ExistingArchive.zip"))
- {
- zip.AddFile("NewData.csv");
- zip.Save("UpdatedArchive.zip");
- }
-
-
-
- Using zip As ZipFile = ZipFile.Read("ExistingArchive.zip")
- zip.AddFile("NewData.csv")
- zip.Save("UpdatedArchive.zip")
- End Using
-
-
-
- using (var zip = new Ionic.Zip.ZipFile())
- {
- zip.CompressionLevel= Ionic.Zlib.CompressionLevel.BestCompression;
- zip.Password = "VerySecret.";
- zip.Encryption = EncryptionAlgorithm.WinZipAes128;
- zip.AddFile(sourceFileName);
- MemoryStream output = new MemoryStream();
- zip.Save(output);
-
- byte[] zipbytes = output.ToArray();
- }
-
-
- using (var fs = new FileSteeam(filename, FileMode.Open))
- {
- using (var zip = Ionic.Zip.ZipFile.Read(inputStream))
- {
- zip.AddEntry("Name1.txt", "this is the content");
- zip.Save(inputStream); // NO NO NO!!
- }
- }
-
-
-
- using (var zip = Ionic.Zip.ZipFile.Read(filename))
- {
- zip.AddEntry("Name1.txt", "this is the content");
- zip.Save(); // YES!
- }
-
-
-
- string DirectoryPath = "c:\\Documents\\Project7";
- using (ZipFile zip = new ZipFile())
- {
- zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath));
- zip.Comment = "This will be embedded into a self-extracting console-based exe";
- zip.SaveSelfExtractor("archive.exe", SelfExtractorFlavor.ConsoleApplication);
- }
-
-
- Dim DirectoryPath As String = "c:\Documents\Project7"
- Using zip As New ZipFile()
- zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath))
- zip.Comment = "This will be embedded into a self-extracting console-based exe"
- zip.SaveSelfExtractor("archive.exe", SelfExtractorFlavor.ConsoleApplication)
- End Using
-
-
- string DirectoryPath = "c:\\Documents\\Project7";
- using (ZipFile zip = new ZipFile())
- {
- zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath));
- zip.Comment = "This will be embedded into a self-extracting WinForms-based exe";
- var options = new SelfExtractorOptions
- {
- Flavor = SelfExtractorFlavor.WinFormsApplication,
- DefaultExtractDirectory = "%USERPROFILE%\\ExtractHere",
- PostExtractCommandLine = ExeToRunAfterExtract,
- SfxExeWindowTitle = "My Custom Window Title",
- RemoveUnpackedFilesAfterExecute = true
- };
- zip.SaveSelfExtractor("archive.exe", options);
- }
-
-
- Dim DirectoryPath As String = "c:\Documents\Project7"
- Using zip As New ZipFile()
- zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath))
- zip.Comment = "This will be embedded into a self-extracting console-based exe"
- Dim options As New SelfExtractorOptions()
- options.Flavor = SelfExtractorFlavor.WinFormsApplication
- options.DefaultExtractDirectory = "%USERPROFILE%\\ExtractHere"
- options.PostExtractCommandLine = ExeToRunAfterExtract
- options.SfxExeWindowTitle = "My Custom Window Title"
- options.RemoveUnpackedFilesAfterExecute = True
- zip.SaveSelfExtractor("archive.exe", options)
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- // To just match on filename wildcards,
- // use the shorthand form of the selectionCriteria string.
- zip.AddSelectedFiles("*.csv");
- zip.Save(PathToZipArchive);
- }
-
-
- Using zip As ZipFile = New ZipFile()
- zip.AddSelectedFiles("*.csv")
- zip.Save(PathToZipArchive)
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- // Use a compound expression in the selectionCriteria string.
- zip.AddSelectedFiles("name = *.xml and size > 1024kb", true);
- zip.Save(PathToZipArchive);
- }
-
-
- Using zip As ZipFile = New ZipFile()
- ' Use a compound expression in the selectionCriteria string.
- zip.AddSelectedFiles("name = *.xml and size > 1024kb", true)
- zip.Save(PathToZipArchive)
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- // Use a compound expression in the selectionCriteria string.
- zip.AddSelectedFiles("name = *.xml and size > 1024kb", "d:\\rawdata");
- zip.Save(PathToZipArchive);
- }
-
-
-
- Using zip As ZipFile = New ZipFile()
- ' Use a compound expression in the selectionCriteria string.
- zip.AddSelectedFiles("name = *.xml and size > 1024kb", "d:\rawdata)
- zip.Save(PathToZipArchive)
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- // Use a compound expression in the selectionCriteria string.
- zip.AddSelectedFiles("name = *.csv and mtime > 2009-02-14", "files", true);
- zip.Save(PathToZipArchive);
- }
-
-
- Using zip As ZipFile = New ZipFile()
- ' Use a compound expression in the selectionCriteria string.
- zip.AddSelectedFiles("name = *.csv and mtime > 2009-02-14", "files", true)
- zip.Save(PathToZipArchive)
- End Using
-
-
- Using Zip As ZipFile = New ZipFile(zipfile)
- Zip.AddSelectedFfiles("name != 'excludethis\*.*'", datapath, True)
- Zip.Save()
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- // Use a compound expression in the selectionCriteria string.
- zip.AddSelectedFiles("name = *.psd and mtime > 2009-02-14", "photos", "content");
- zip.Save(PathToZipArchive);
- }
-
-
- Using zip As ZipFile = New ZipFile
- zip.AddSelectedFiles("name = *.psd and mtime > 2009-02-14", "photos", "content")
- zip.Save(PathToZipArchive)
- End Using
-
-
- using (ZipFile zip = new ZipFile())
- {
- zip.AddSelectedFiles("name != *.pst", SourceDirectory, "backup", true);
- zip.Save(PathToZipArchive);
- }
-
-
- Using zip As ZipFile = New ZipFile
- zip.AddSelectedFiles("name != *.pst", SourceDirectory, "backup", true)
- zip.Save(PathToZipArchive)
- End Using
-
-
- using (ZipFile zip1 = ZipFile.Read(ZipFileName))
- {
- var PhotoShopFiles = zip1.SelectEntries("*.psd");
- foreach (ZipEntry psd in PhotoShopFiles)
- {
- psd.Extract();
- }
- }
-
-
- Using zip1 As ZipFile = ZipFile.Read(ZipFileName)
- Dim PhotoShopFiles as ICollection(Of ZipEntry)
- PhotoShopFiles = zip1.SelectEntries("*.psd")
- Dim psd As ZipEntry
- For Each psd In PhotoShopFiles
- psd.Extract
- Next
- End Using
-
-
- using (ZipFile zip1 = ZipFile.Read(ZipFileName))
- {
- var UpdatedPhotoShopFiles = zip1.SelectEntries("*.psd", "UpdatedFiles");
- foreach (ZipEntry e in UpdatedPhotoShopFiles)
- {
- // prompt for extract here
- if (WantExtract(e.FileName))
- e.Extract();
- }
- }
-
-
- Using zip1 As ZipFile = ZipFile.Read(ZipFileName)
- Dim UpdatedPhotoShopFiles As ICollection(Of ZipEntry) = zip1.SelectEntries("*.psd", "UpdatedFiles")
- Dim e As ZipEntry
- For Each e In UpdatedPhotoShopFiles
- ' prompt for extract here
- If Me.WantExtract(e.FileName) Then
- e.Extract
- End If
- Next
- End Using
-
-
- using (ZipFile zip1 = ZipFile.Read(ZipFileName))
- {
- // remove all entries from prior to Jan 1, 2008
- zip1.RemoveEntries("mtime < 2008-01-01");
- // don't forget to save the archive!
- zip1.Save();
- }
-
-
- Using zip As ZipFile = ZipFile.Read(ZipFileName)
- ' remove all entries from prior to Jan 1, 2008
- zip1.RemoveEntries("mtime < 2008-01-01")
- ' do not forget to save the archive!
- zip1.Save
- End Using
-
-
- using (ZipFile zip1 = ZipFile.Read(ZipFileName))
- {
- // remove all entries from prior to Jan 1, 2008
- zip1.RemoveEntries("mtime < 2008-01-01", "documents");
- // a call to ZipFile.Save will make the modifications permanent
- zip1.Save();
- }
-
-
- Using zip As ZipFile = ZipFile.Read(ZipFileName)
- ' remove all entries from prior to Jan 1, 2008
- zip1.RemoveEntries("mtime < 2008-01-01", "documents")
- ' a call to ZipFile.Save will make the modifications permanent
- zip1.Save
- End Using
-
-
- using (ZipFile zip = ZipFile.Read(zipArchiveName))
- {
- zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15");
- }
-
-
- using (ZipFile zip = ZipFile.Read(zipArchiveName))
- {
- zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15",
- ExtractExistingFileAction.OverwriteSilently);
- }
-
-
- using (ZipFile zip = ZipFile.Read(zipArchiveName))
- {
- zip.ExtractSelectedEntries("name = *.xml and mtime > 2009-01-15","unpack");
- }
-
-
- using (ZipFile zip = ZipFile.Read(zipArchiveName))
- {
- zip.ExtractSelectedEntries("name = *.xml or size > 100000",
- null,
- "unpack",
- ExtractExistingFileAction.DontOverwrite);
- }
-
-
- using (ZipFile zip = ZipFile.Read(zipfile))
- {
- bool header = true;
- foreach (ZipEntry e in zip)
- {
- if (header)
- {
- System.Console.WriteLine("Zipfile: {0}", zip.Name);
- System.Console.WriteLine("Version Needed: 0x{0:X2}", e.VersionNeeded);
- System.Console.WriteLine("BitField: 0x{0:X2}", e.BitField);
- System.Console.WriteLine("Compression Method: 0x{0:X2}", e.CompressionMethod);
- System.Console.WriteLine("\n{1,-22} {2,-6} {3,4} {4,-8} {0}",
- "Filename", "Modified", "Size", "Ratio", "Packed");
- System.Console.WriteLine(new System.String('-', 72));
- header = false;
- }
-
- System.Console.WriteLine("{1,-22} {2,-6} {3,4:F0}% {4,-8} {0}",
- e.FileName,
- e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
- e.UncompressedSize,
- e.CompressionRatio,
- e.CompressedSize);
-
- e.Extract();
- }
- }
-
-
-
- Dim ZipFileToExtract As String = "c:\foo.zip"
- Using zip As ZipFile = ZipFile.Read(ZipFileToExtract)
- Dim header As Boolean = True
- Dim e As ZipEntry
- For Each e In zip
- If header Then
- Console.WriteLine("Zipfile: {0}", zip.Name)
- Console.WriteLine("Version Needed: 0x{0:X2}", e.VersionNeeded)
- Console.WriteLine("BitField: 0x{0:X2}", e.BitField)
- Console.WriteLine("Compression Method: 0x{0:X2}", e.CompressionMethod)
- Console.WriteLine(ChrW(10) & "{1,-22} {2,-6} {3,4} {4,-8} {0}", _
- "Filename", "Modified", "Size", "Ratio", "Packed" )
- Console.WriteLine(New String("-"c, 72))
- header = False
- End If
- Console.WriteLine("{1,-22} {2,-6} {3,4:F0}% {4,-8} {0}", _
- e.FileName, _
- e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), _
- e.UncompressedSize, _
- e.CompressionRatio, _
- e.CompressedSize )
- e.Extract
- Next
- End Using
-
-
- private void Unzip()
- {
- byte[] buffer= new byte[2048];
- int n;
- using (var raw = File.Open(inputFileName, FileMode.Open, FileAccess.Read))
- {
- using (var input= new ZipInputStream(raw))
- {
- ZipEntry e;
- while (( e = input.GetNextEntry()) != null)
- {
- if (e.IsDirectory) continue;
- string outputPath = Path.Combine(extractDir, e.FileName);
- using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
- {
- while ((n= input.Read(buffer, 0, buffer.Length)) > 0)
- {
- output.Write(buffer,0,n);
- }
- }
- }
- }
- }
- }
-
-
-
- Private Sub UnZip()
- Dim inputFileName As String = "MyArchive.zip"
- Dim extractDir As String = "extract"
- Dim buffer As Byte() = New Byte(2048) {}
- Using raw As FileStream = File.Open(inputFileName, FileMode.Open, FileAccess.Read)
- Using input As ZipInputStream = New ZipInputStream(raw)
- Dim e As ZipEntry
- Do While (Not e = input.GetNextEntry Is Nothing)
- If Not e.IsDirectory Then
- Using output As FileStream = File.Open(Path.Combine(extractDir, e.FileName), _
- FileMode.Create, FileAccess.ReadWrite)
- Dim n As Integer
- Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
- output.Write(buffer, 0, n)
- Loop
- End Using
- End If
- Loop
- End Using
- End Using
- End Sub
-
-
- private void Unzip()
- {
- byte[] buffer= new byte[2048];
- int n;
- using (var input= new ZipInputStream(inputFileName))
- {
- ZipEntry e;
- while (( e = input.GetNextEntry()) != null)
- {
- if (e.IsDirectory) continue;
- string outputPath = Path.Combine(extractDir, e.FileName);
- using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
- {
- while ((n= input.Read(buffer, 0, buffer.Length)) > 0)
- {
- output.Write(buffer,0,n);
- }
- }
- }
- }
- }
-
-
-
- Private Sub UnZip()
- Dim inputFileName As String = "MyArchive.zip"
- Dim extractDir As String = "extract"
- Dim buffer As Byte() = New Byte(2048) {}
- Using input As ZipInputStream = New ZipInputStream(inputFileName)
- Dim e As ZipEntry
- Do While (Not e = input.GetNextEntry Is Nothing)
- If Not e.IsDirectory Then
- Using output As FileStream = File.Open(Path.Combine(extractDir, e.FileName), _
- FileMode.Create, FileAccess.ReadWrite)
- Dim n As Integer
- Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
- output.Write(buffer, 0, n)
- Loop
- End Using
- End If
- Loop
- End Using
- End Sub
-
-
- byte[] buffer= new byte[2048];
- int n;
- using (var raw = File.Open(_inputFileName, FileMode.Open, FileAccess.Read ))
- {
- using (var input= new ZipInputStream(raw))
- {
- ZipEntry e;
- while (( e = input.GetNextEntry()) != null)
- {
- input.Password = PasswordForEntry(e.FileName);
- if (e.IsDirectory) continue;
- string outputPath = Path.Combine(_extractDir, e.FileName);
- using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
- {
- while ((n= input.Read(buffer,0,buffer.Length)) > 0)
- {
- output.Write(buffer,0,n);
- }
- }
- }
- }
- }
-
-
-
- private void Zipup()
- {
- if (filesToZip.Count == 0)
- {
- System.Console.WriteLine("Nothing to do.");
- return;
- }
-
- using (var raw = File.Open(_outputFileName, FileMode.Create, FileAccess.ReadWrite ))
- {
- using (var output= new ZipOutputStream(raw))
- {
- output.Password = "VerySecret!";
- output.Encryption = EncryptionAlgorithm.WinZipAes256;
-
- foreach (string inputFileName in filesToZip)
- {
- System.Console.WriteLine("file: {0}", inputFileName);
-
- output.PutNextEntry(inputFileName);
- using (var input = File.Open(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write ))
- {
- byte[] buffer= new byte[2048];
- int n;
- while ((n= input.Read(buffer,0,buffer.Length)) > 0)
- {
- output.Write(buffer,0,n);
- }
- }
- }
- }
- }
- }
-
-
-
- Private Sub Zipup()
- Dim outputFileName As String = "XmlData.zip"
- Dim filesToZip As String() = Directory.GetFiles(".", "*.xml")
- If (filesToZip.Length = 0) Then
- Console.WriteLine("Nothing to do.")
- Else
- Using raw As FileStream = File.Open(outputFileName, FileMode.Create, FileAccess.ReadWrite)
- Using output As ZipOutputStream = New ZipOutputStream(raw)
- output.Password = "VerySecret!"
- output.Encryption = EncryptionAlgorithm.WinZipAes256
- Dim inputFileName As String
- For Each inputFileName In filesToZip
- Console.WriteLine("file: {0}", inputFileName)
- output.PutNextEntry(inputFileName)
- Using input As FileStream = File.Open(inputFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
- Dim n As Integer
- Dim buffer As Byte() = New Byte(2048) {}
- Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
- output.Write(buffer, 0, n)
- Loop
- End Using
- Next
- End Using
- End Using
- End If
- End Sub
-
-
- private void Zipup()
- {
- if (filesToZip.Count == 0)
- {
- System.Console.WriteLine("Nothing to do.");
- return;
- }
-
- using (var output= new ZipOutputStream(outputFileName))
- {
- output.Password = "VerySecret!";
- output.Encryption = EncryptionAlgorithm.WinZipAes256;
-
- foreach (string inputFileName in filesToZip)
- {
- System.Console.WriteLine("file: {0}", inputFileName);
-
- output.PutNextEntry(inputFileName);
- using (var input = File.Open(inputFileName, FileMode.Open, FileAccess.Read,
- FileShare.Read | FileShare.Write ))
- {
- byte[] buffer= new byte[2048];
- int n;
- while ((n= input.Read(buffer,0,buffer.Length)) > 0)
- {
- output.Write(buffer,0,n);
- }
- }
- }
- }
- }
-
-
-
- Private Sub Zipup()
- Dim outputFileName As String = "XmlData.zip"
- Dim filesToZip As String() = Directory.GetFiles(".", "*.xml")
- If (filesToZip.Length = 0) Then
- Console.WriteLine("Nothing to do.")
- Else
- Using output As ZipOutputStream = New ZipOutputStream(outputFileName)
- output.Password = "VerySecret!"
- output.Encryption = EncryptionAlgorithm.WinZipAes256
- Dim inputFileName As String
- For Each inputFileName In filesToZip
- Console.WriteLine("file: {0}", inputFileName)
- output.PutNextEntry(inputFileName)
- Using input As FileStream = File.Open(inputFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
- Dim n As Integer
- Dim buffer As Byte() = New Byte(2048) {}
- Do While (n = input.Read(buffer, 0, buffer.Length) > 0)
- output.Write(buffer, 0, n)
- Loop
- End Using
- Next
- End Using
- End If
- End Sub
-
-
- private void Zipup()
- {
- using (FileStream fs raw = File.Open(_outputFileName, FileMode.Create, FileAccess.ReadWrite ))
- {
- using (var output= new ZipOutputStream(fs))
- {
- output.Password = "VerySecret!";
- output.Encryption = EncryptionAlgorithm.WinZipAes256;
- output.PutNextEntry("entry1.txt");
- byte[] buffer= System.Text.Encoding.ASCII.GetBytes("This is the content for entry #1.");
- output.Write(buffer,0,buffer.Length);
- output.PutNextEntry("entry2.txt"); // this will be zero length
- output.PutNextEntry("entry3.txt");
- buffer= System.Text.Encoding.ASCII.GetBytes("This is the content for entry #3.");
- output.Write(buffer,0,buffer.Length);
- }
- }
- }
-
-
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
- {
- using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n;
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
-
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(fileToCompress & ".deflated")
- Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
- {
- using (Stream compressor = new DeflateStream(raw,
- CompressionMode.Compress,
- CompressionLevel.BestCompression))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n= -1;
- while (n != 0)
- {
- if (n > 0)
- compressor.Write(buffer, 0, n);
- n= input.Read(buffer, 0, buffer.Length);
- }
- }
- }
- }
-
-
-
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(fileToCompress & ".deflated")
- Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
- {
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n= -1;
- while (n != 0)
- {
- if (n > 0)
- compressor.Write(buffer, 0, n);
- n= input.Read(buffer, 0, buffer.Length);
- }
- }
- }
- // can write additional data to the output stream here
- }
-
-
-
- Using output As FileStream = File.Create(fileToCompress & ".deflated")
- Using input As Stream = File.OpenRead(fileToCompress)
- Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- ' can write additional data to the output stream here.
- End Using
-
-
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(outputFile))
- {
- using (Stream compressor = new GZipStream(raw, CompressionMode.Compress))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n;
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
- Dim outputFile As String = (fileToCompress & ".compressed")
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(outputFile)
- Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- private void GunZipFile(string filename)
- {
- if (!filename.EndsWith(".gz))
- throw new ArgumentException("filename");
- var DecompressedFile = filename.Substring(0,filename.Length-3);
- byte[] working = new byte[WORKING_BUFFER_SIZE];
- int n= 1;
- using (System.IO.Stream input = System.IO.File.OpenRead(filename))
- {
- using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
- {
- using (var output = System.IO.File.Create(DecompressedFile))
- {
- while (n !=0)
- {
- n= decompressor.Read(working, 0, working.Length);
- if (n > 0)
- {
- output.Write(working, 0, n);
- }
- }
- }
- }
- }
- }
-
-
-
- Private Sub GunZipFile(ByVal filename as String)
- If Not (filename.EndsWith(".gz)) Then
- Throw New ArgumentException("filename")
- End If
- Dim DecompressedFile as String = filename.Substring(0,filename.Length-3)
- Dim working(WORKING_BUFFER_SIZE) as Byte
- Dim n As Integer = 1
- Using input As Stream = File.OpenRead(filename)
- Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True)
- Using output As Stream = File.Create(UncompressedFile)
- Do
- n= decompressor.Read(working, 0, working.Length)
- If n > 0 Then
- output.Write(working, 0, n)
- End IF
- Loop While (n > 0)
- End Using
- End Using
- End Using
- End Sub
-
-
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(fileToCompress + ".gz"))
- {
- using (Stream compressor = new GZipStream(raw,
- CompressionMode.Compress,
- CompressionLevel.BestCompression))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n;
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
-
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(fileToCompress & ".gz")
- Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(outputFile))
- {
- using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n;
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
- Dim outputFile As String = (fileToCompress & ".compressed")
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(outputFile)
- Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- byte[] working = new byte[WORKING_BUFFER_SIZE];
- using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
- {
- using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
- {
- using (var output = System.IO.File.Create(_DecompressedFile))
- {
- int n;
- while ((n= decompressor.Read(working, 0, working.Length)) !=0)
- {
- output.Write(working, 0, n);
- }
- }
- }
- }
-
-
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n= -1;
- String outputFile = fileToCompress + ".compressed";
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(outputFile))
- {
- using (Stream compressor = new ParallelDeflateOutputStream(raw))
- {
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Dim outputFile As String = (fileToCompress & ".compressed")
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(outputFile)
- Using compressor As Stream = New ParallelDeflateOutputStream(raw)
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- ParallelDeflateOutputStream deflater = null;
- foreach (var inputFile in listOfFiles)
- {
- string outputFile = inputFile + ".compressed";
- using (System.IO.Stream input = System.IO.File.OpenRead(inputFile))
- {
- using (var outStream = System.IO.File.Create(outputFile))
- {
- if (deflater == null)
- deflater = new ParallelDeflateOutputStream(outStream,
- CompressionLevel.Best,
- CompressionStrategy.Default,
- true);
- deflater.Reset(outStream);
-
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- deflater.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
- var adler = Adler.Adler32(0, null, 0, 0);
- adler = Adler.Adler32(adler, buffer, index, length);
-
-
- private void InflateBuffer()
- {
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
- ZlibCodec decompressor = new ZlibCodec();
-
- Console.WriteLine("\n============================================");
- Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
- MemoryStream ms = new MemoryStream(DecompressedBytes);
-
- int rc = decompressor.InitializeInflate();
-
- decompressor.InputBuffer = CompressedBytes;
- decompressor.NextIn = 0;
- decompressor.AvailableBytesIn = CompressedBytes.Length;
-
- decompressor.OutputBuffer = buffer;
-
- // pass 1: inflate
- do
- {
- decompressor.NextOut = 0;
- decompressor.AvailableBytesOut = buffer.Length;
- rc = decompressor.Inflate(FlushType.None);
-
- if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
- throw new Exception("inflating: " + decompressor.Message);
-
- ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
- }
- while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
-
- // pass 2: finish and flush
- do
- {
- decompressor.NextOut = 0;
- decompressor.AvailableBytesOut = buffer.Length;
- rc = decompressor.Inflate(FlushType.Finish);
-
- if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
- throw new Exception("inflating: " + decompressor.Message);
-
- if (buffer.Length - decompressor.AvailableBytesOut > 0)
- ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
- }
- while (decompressor.AvailableBytesIn > 0 || decompressor.AvailableBytesOut == 0);
-
- decompressor.EndInflate();
- }
-
-
-
- int bufferSize = 40000;
- byte[] CompressedBytes = new byte[bufferSize];
- byte[] DecompressedBytes = new byte[bufferSize];
-
- ZlibCodec compressor = new ZlibCodec();
-
- compressor.InitializeDeflate(CompressionLevel.Default);
-
- compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
- compressor.NextIn = 0;
- compressor.AvailableBytesIn = compressor.InputBuffer.Length;
-
- compressor.OutputBuffer = CompressedBytes;
- compressor.NextOut = 0;
- compressor.AvailableBytesOut = CompressedBytes.Length;
-
- while (compressor.TotalBytesIn != TextToCompress.Length && compressor.TotalBytesOut < bufferSize)
- {
- compressor.Deflate(FlushType.None);
- }
-
- while (true)
- {
- int rc= compressor.Deflate(FlushType.Finish);
- if (rc == ZlibConstants.Z_STREAM_END) break;
- }
-
- compressor.EndDeflate();
-
-
-
- private void DeflateBuffer(CompressionLevel level)
- {
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
- ZlibCodec compressor = new ZlibCodec();
-
- Console.WriteLine("\n============================================");
- Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
- MemoryStream ms = new MemoryStream();
-
- int rc = compressor.InitializeDeflate(level);
-
- compressor.InputBuffer = UncompressedBytes;
- compressor.NextIn = 0;
- compressor.AvailableBytesIn = UncompressedBytes.Length;
-
- compressor.OutputBuffer = buffer;
-
- // pass 1: deflate
- do
- {
- compressor.NextOut = 0;
- compressor.AvailableBytesOut = buffer.Length;
- rc = compressor.Deflate(FlushType.None);
-
- if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
- throw new Exception("deflating: " + compressor.Message);
-
- ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
- }
- while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
-
- // pass 2: finish and flush
- do
- {
- compressor.NextOut = 0;
- compressor.AvailableBytesOut = buffer.Length;
- rc = compressor.Deflate(FlushType.Finish);
-
- if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
- throw new Exception("deflating: " + compressor.Message);
-
- if (buffer.Length - compressor.AvailableBytesOut > 0)
- ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
- }
- while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
-
- compressor.EndDeflate();
-
- ms.Seek(0, SeekOrigin.Begin);
- CompressedBytes = new byte[compressor.TotalBytesOut];
- ms.Read(CompressedBytes, 0, CompressedBytes.Length);
- }
-
-
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
- {
- using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n;
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(fileToCompress & ".zlib")
- Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (var raw = System.IO.File.Create(fileToCompress + ".zlib"))
- {
- using (Stream compressor = new ZlibStream(raw,
- CompressionMode.Compress,
- CompressionLevel.BestCompression))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n;
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- }
-
-
-
- Using input As Stream = File.OpenRead(fileToCompress)
- Using raw As FileStream = File.Create(fileToCompress & ".zlib")
- Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- End Using
-
-
- using (var output = System.IO.File.Create(fileToCompress + ".zlib"))
- {
- using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
- {
- using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
- {
- byte[] buffer = new byte[WORKING_BUFFER_SIZE];
- int n;
- while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressor.Write(buffer, 0, n);
- }
- }
- }
- // can write additional data to the output stream here
- }
-
-
- Using output As FileStream = File.Create(fileToCompress & ".zlib")
- Using input As Stream = File.OpenRead(fileToCompress)
- Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
- Dim buffer As Byte() = New Byte(4096) {}
- Dim n As Integer = -1
- Do While (n <> 0)
- If (n > 0) Then
- compressor.Write(buffer, 0, n)
- End If
- n = input.Read(buffer, 0, buffer.Length)
- Loop
- End Using
- End Using
- ' can write additional data to the output stream here.
- End Using
-
- file.RemoveTags (file.TagTypes & ~file.TagTypesOnDisk);
- file.RemoveTags (file.TagTypes & ~file.TagTypesOnDisk);
-
- using System;
- using TagLib;
-
- public class ExceptionTest
- {
- public static void Main ()
- {
- try {
- File file = File.Create ("partial.mp3"); // Partial download.
- } catch (CorruptFileException e) {
- Console.WriteLine ("That file is corrupt: {0}", e.ToString ());
- }
- }
- }
-
-
- #using <System.dll>
- #using <taglib-sharp.dll>
-
- using System;
- using TagLib;
-
- void main ()
- {
- try {
- File file = File::Create ("partial.mp3"); // Partial download.
- } catch (CorruptFileException^ e) {
- Console::WriteLine ("That file is corrupt: {0}", e);
- }
- }
-
-
- Imports System
- Imports TagLib
-
- Public Class ExceptionTest
- Public Shared Sub Main ()
- Try
- file As File = File.Create ("partial.mp3") ' Partial download.
- Catch e As CorruptFileException
- Console.WriteLine ("That file is corrupt: {0}", e.ToString ());
- End Try
- End Sub
- End Class
-
-
- import System
- import TagLib
-
- try:
- file As File = File.Create ("partial.mp3") # Partial download.
- catch e as CorruptFileException:
- Console.WriteLine ("That file is corrupt: {0}", e.ToString ());
-
- string [] SetMoods (TagLib.File file, params string[] moods)
- {
- TagLib.Id3v2.Tag id3 = file.GetTag (TagLib.TagTypes.Id3v2, true);
- if (id3 != null)
- id3.SetTextFrame ("TMOO", moods);
-
- TagLib.Asf.Tag asf = file.GetTag (TagLib.TagTypes.Asf, true);
- if (asf != null)
- asf.SetDescriptorStrings (moods, "WM/Mood", "Mood");
-
- TagLib.Ape.Tag ape = file.GetTag (TagLib.TagTypes.Ape);
- if (ape != null)
- ape.SetValue ("MOOD", moods);
-
- // Whatever tag types you want...
- }
- static string [] GetMoods (TagLib.File file)
- {
- TagLib.Id3v2.Tag id3 = file.GetTag (TagLib.TagTypes.Id3v2);
- if (id3 != null) {
- TextIdentificationFrame f = TextIdentificationFrame.Get (this, "TMOO");
- if (f != null)
- return f.FieldList.ToArray ();
- }
-
- TagLib.Asf.Tag asf = file.GetTag (TagLib.TagTypes.Asf);
- if (asf != null) {
- string [] value = asf.GetDescriptorStrings ("WM/Mood", "Mood");
- if (value.Length > 0)
- return value;
- }
-
- TagLib.Ape.Tag ape = file.GetTag (TagLib.TagTypes.Ape);
- if (ape != null) {
- Item item = ape.GetItem ("MOOD");
- if (item != null)
- return item.ToStringArray ();
- }
-
- // Whatever tag types you want...
-
- return new string [] {};
- }
- using TagLib;
- using Gnome.Vfs;
-
- public class ReadTitle
- {
- public static void Main (string [] args)
- {
- if (args.Length != 1)
- return;
-
- Gnome.Vfs.Vfs.Initialize ();
-
- try {
- TagLib.File file = TagLib.File.Create (
- new VfsFileAbstraction (args [0]));
- System.Console.WriteLine (file.Tag.Title);
- } finally {
- Vfs.Shutdown()
- }
- }
- }
-
- public class VfsFileAbstraction : TagLib.File.IFileAbstraction
- {
- private string name;
-
- public VfsFileAbstraction (string file)
- {
- name = file;
- }
-
- public string Name {
- get { return name; }
- }
-
- public System.IO.Stream ReadStream {
- get { return new VfsStream(Name, System.IO.FileMode.Open); }
- }
-
- public System.IO.Stream WriteStream {
- get { return new VfsStream(Name, System.IO.FileMode.Open); }
- }
-
- public void CloseStream (System.IO.Stream stream)
- {
- stream.Close ();
- }
- }
- import TagLib from "taglib-sharp.dll"
- import Gnome.Vfs from "gnome-vfs-sharp"
-
- class VfsFileAbstraction (TagLib.File.IFileAbstraction):
-
- _name as string
-
- def constructor(file as string):
- _name = file
-
- Name:
- get:
- return _name
-
- ReadStream:
- get:
- return VfsStream(_name, FileMode.Open)
-
- WriteStream:
- get:
- return VfsStream(_name, FileMode.Open)
-
- if len(argv) == 1:
- Vfs.Initialize()
-
- try:
- file as TagLib.File = TagLib.File.Create (VfsFileAbstraction (argv[0]))
- print file.Tag.Title
- ensure:
- Vfs.Shutdown()
- file.RemoveTags (file.TagTypes & ~file.TagTypesOnDisk);
-
- public Frame Creator (TagLib.ByteVector data, TagLib.Id3v2.FrameHeader header)
- {
- if (header.FrameId == "RVRB")
- return new ReverbFrame (data, header);
- else
- return null;
- }
- ...
- TagLib.Id3v2.FrameFactor.AddFrameCreator (ReverbFrame.Creator);
-
-
- using TagLib;
- using TagLib.Id3v2;
-
- public static class AddId3v2Picture
- {
- public static void Main (string [] args)
- {
- if (args.Length != 2)
- throw new ApplicationException (
- "USAGE: AddId3v2Picture.exe AUDIO_FILE PICTURE_FILE");
-
- // Create the file. Can throw file to TagLib# exceptions.
- File file = File.Create (args [0]);
-
- // Get or create the ID3v2 tag.
- TagLib.Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, true) as TagLib.Id3v2.Tag;
- if (tag == null)
- throw new ApplicationException ("File does not support ID3v2 tags.");
-
- // Create a picture. Can throw file related exceptions.
- TagLib.Picture picture = TagLib.Picture.CreateFromPath (path);
-
- // Add a new picture frame to the tag.
- tag.AddFrame (new AttachedPictureFrame (picture));
-
- // Save the file.
- file.Save ();
- }
- }
-
-
- using TagLib;
- using TagLib.Id3v2;
-
- public static class SetId3v2Cover
- {
- public static void Main (string [] args)
- {
- if (args.Length != 3)
- throw new ApplicationException (
- "USAGE: SetId3v2Cover.exe AUDIO_FILE PICTURE_FILE DESCRIPTION");
-
- // Create the file. Can throw file to TagLib# exceptions.
- File file = File.Create (args [0]);
-
- // Get or create the ID3v2 tag.
- TagLib.Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, true) as TagLib.Id3v2.Tag;
- if (tag == null)
- throw new ApplicationException ("File does not support ID3v2 tags.");
-
- // Create a picture. Can throw file related exceptions.
- TagLib.Picture picture = TagLib.Picture.CreateFromPath (args [1]);
-
- // Get or create the picture frame.
- AttachedPictureFrame frame = AttachedPictureFrame.Get (
- tag, args [2], PictureType.FrontCover, true);
-
- // Set the data from the picture.
- frame.MimeType = picture.MimeType;
- frame.Data = picture.data;
-
- // Save the file.
- file.Save ();
- }
- }
-
-
- using TagLib;
- using TagLib.Id3v2;
-
- public static class AddId3v2Picture
- {
- public static void Main (string [] args)
- {
- if (args.Length != 2)
- throw new ApplicationException (
- "USAGE: AddId3v2Picture.exe AUDIO_FILE PICTURE_FILE");
-
- // Create the file. Can throw file to TagLib# exceptions.
- File file = File.Create (args [0]);
-
- // Get or create the ID3v2 tag.
- TagLib.Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, true) as TagLib.Id3v2.Tag;
- if (tag == null)
- throw new ApplicationException ("File does not support ID3v2 tags.");
-
- // Create a picture. Can throw file related exceptions.
- TagLib.Picture picture = TagLib.Picture.CreateFromPath (path);
-
- // Add a new picture frame to the tag.
- tag.AddFrame (new AttachedPictureFrame (picture));
-
- // Save the file.
- file.Save ();
- }
- }
-
-
- using TagLib;
- using TagLib.Id3v2;
-
- public static class LookupUtil
- {
- public static ByteVector GetTrackEvents(string filename)
- {
- File file = File.Create (filename, ReadStyle.None);
- Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, false) as Id3v2.Tag;
- if (tag == null)
- return new ByteVector ();
-
- EventTimeCodesFrame frame = EventTimeCodesFrame.Get (tag, false);
- if (frame == null)
- return new ByteVector ();
-
- return frame.Data;
- }
- }
-
-
- #using <System.dll>
- #using <taglib-sharp.dll>
-
- using System;
- using TagLib;
- using TagLib::Id3v2;
-
- public ref class LookupUtil abstract sealed
- {
- public:
- static ByteVector^ GetTrackEvents (String^ filename)
- {
- File^ file = File::Create (filename, ReadStyle::None);
- Id3v2::Tag^ tag = dynamic_cast<Id3v2::Tag^> (file.GetTag (TagTypes::Id3v2, false));
- if (tag == null)
- return gcnew ByteVector;
-
- EventTimeCodesFrame^ frame = EventTimeCodesFrame::Get (tag, false);
- if (frame == null)
- return gcnew ByteVector;
-
- return frame->Data;
- }
- }
-
-
- Imports TagLib
- Imports TagLib.Id3v2
-
- Public Shared Class LookupUtil
- Public Shared Sub GetTrackEvents (filename As String) As TagLib.ByteVector
- Dim file As File = File.Create (filename, ReadStyle.None)
- Dim tag As Id3v2.Tag = file.GetTag (TagTypes.Id3v2, False)
- If tag Is Nothing Return New ByteVector ()
-
- Dim frame As EventTimeCodesFrame = EventTimeCodesFrame.Get (tag, False)
- If frame Is Nothing Return New ByteVector ()
-
- Return frame.Data
- End Sub
- End Class
-
-
- import TagLib
- import TagLib.Id3v2
-
- public static class LookupUtil:
- static def GetTrackEvents (filename as string) as TagLib.ByteVector:
- file as File = File.Create (filename, ReadStyle.None)
- tag as Id3v2.Tag = file.GetTag (TagTypes.Id3v2, false)
- if tag == null:
- return ByteVector ()
-
- frame as EventTimeCodesFrame = EventTimeCodesFrame.Get (tag, false)
- if frame == null:
- return ByteVector ()
-
- return frame.Data
-
-
- using TagLib;
- using TagLib.Id3v2;
-
- public static class LookupUtil
- {
- public static ByteVector GetCdIdentifier (string filename)
- {
- File file = File.Create (filename, ReadStyle.None);
- Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, false) as Id3v2.Tag;
- if (tag == null)
- return new ByteVector ();
-
- MusicCdIdentifierFrame frame = MusicCdIdentifierFrame.Get (tag, false);
- if (frame == null)
- return new ByteVector ();
-
- return frame.Data;
- }
- }
-
-
- #using <System.dll>
- #using <taglib-sharp.dll>
-
- using System;
- using TagLib;
- using TagLib::Id3v2;
-
- public ref class LookupUtil abstract sealed
- {
- public:
- static ByteVector^ GetCdIdentifier (String^ filename)
- {
- File^ file = File::Create (filename, ReadStyle::None);
- Id3v2::Tag^ tag = dynamic_cast<Id3v2::Tag^> (file.GetTag (TagTypes::Id3v2, false));
- if (tag == null)
- return gcnew ByteVector;
-
- MusicCdIdentifierFrame^ frame = MusicCdIdentifierFrame::Get (tag, false);
- if (frame == null)
- return gcnew ByteVector;
-
- return frame->Data;
- }
- }
-
-
- Imports TagLib
- Imports TagLib.Id3v2
-
- Public Shared Class LookupUtil
- Public Shared Sub GetCdIdentifier (filename As String) As TagLib.ByteVector
- Dim file As File = File.Create (filename, ReadStyle.None)
- Dim tag As Id3v2.Tag = file.GetTag (TagTypes.Id3v2, False)
- If tag Is Nothing Return New ByteVector ()
-
- Dim frame As MusicCdIdentifierFrame = MusicCdIdentifierFrame.Get (tag, False)
- If frame Is Nothing Return New ByteVector ()
-
- Return frame.Data
- End Sub
- End Class
-
-
- import TagLib
- import TagLib.Id3v2
-
- public static class LookupUtil:
- static def GetCdIdentifier (filename as string) as TagLib.ByteVector:
- file as File = File.Create (filename, ReadStyle.None)
- tag as Id3v2.Tag = file.GetTag (TagTypes.Id3v2, false)
- if tag == null:
- return ByteVector ()
-
- frame as MusicCdIdentifierFrame = MusicCdIdentifierFrame.Get (tag, false)
- if frame == null:
- return ByteVector ()
-
- return frame.Data
-
-
- using TagLib;
- using TagLib.Id3v2;
-
- public static class TrackUtil
- {
- public static int GetPlayCount (string filename)
- {
- File file = File.Create (filename, ReadStyle.None);
- Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, false) as Id3v2.Tag;
- if (tag == null)
- return 0;
-
- PlayCountFrame frame = PlayCountFrame.Get (tag, false);
- if (frame == null)
- return 0;
-
- return frame.PlayCount;
- }
-
- public static void IncrementPlayCount (string filename)
- {
- File file = File.Create (filename, ReadStyle.None);
- Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, true) as Id3v2.Tag;
- if (tag == null)
- return;
-
- PlayCountFrame.Get (tag, true).PlayCount ++;
- file.Save ();
- }
- }
-
-
- #using <System.dll>
- #using <taglib-sharp.dll>
-
- using System;
- using TagLib;
- using TagLib::Id3v2;
-
- public ref class TrackUtil abstract sealed
- {
- public:
- static int GetPlayCount (String^ filename)
- {
- File^ file = File.Create (filename, ReadStyle.None);
- Id3v2::Tag^ tag = dynamic_cast<Id3v2::Tag^> (file.GetTag (TagTypes::Id3v2, false));
- if (tag == null)
- return 0;
-
- PlayCountFrame^ frame = PlayCountFrame::Get (tag, false);
- if (frame == null)
- return 0;
-
- return frame->PlayCount;
- }
-
- static void IncrementPlayCount (String^ filename)
- {
- File^ file = File::Create (filename, ReadStyle::None);
- Id3v2.Tag^ tag = dynamic_cast<Id3v2::Tag^> (file.GetTag (TagTypes::Id3v2, true));
- if (tag == null)
- return;
-
- PlayCountFrame::Get (tag, true)->PlayCount ++;
- file->Save ();
- }
- }
-
-
- Imports TagLib
- Imports TagLib.Id3v2
-
- Public Shared Class TrackUtil
- Public Shared Sub GetPlayCount (filename As String) As Integer
- Dim file As File = File.Create (filename, ReadStyle.None)
- Dim tag As Id3v2.Tag = file.GetTag (TagTypes.Id3v2, False)
- If tag Is Nothing Then Return 0
-
- Dim frame As PlayCountFrame = PlayCountFrame.Get (tag, False)
- If frame Is Nothing Then Return 0
-
- Return frame.PlayCount
- End Sub
-
- Public Shared Sub IncrementPlayCount (filename As String)
- Dim file As File = File.Create (filename, ReadStyle.None)
- Dim tag As Id3v2.Tag = file.GetTag (TagTypes.Id3v2, True)
- If tag Is Nothing Then Exit Sub
-
- PlayCountFrame.Get (tag, True).PlayCount += 1
- file.Save ()
- End Sub
- End Class
-
-
- import TagLib
- import TagLib.Id3v2
-
- public static class TrackUtil:
- static def GetPlayCount (filename as string) as int:
- file As File = File.Create (filename, ReadStyle.None)
- tag as Id3v2.Tag = file.GetTag (TagTypes.Id3v2, false)
- if tag == null:
- return 0
-
- frame as PlayCountFrame = PlayCountFrame.Get (tag, false)
- if frame == null:
- return 0
-
- return frame.PlayCount
-
- static def IncrementPlayCount (filename as string):
- file as File = File.Create (filename, ReadStyle.None)
- tag as Id3v2.Tag = file.GetTag (TagTypes.Id3v2, True)
- if tag == null:
- return
-
- PlayCountFrame.Get (tag, true).PlayCount ++
- file.Save ()
-
-
- using System;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Text;
- using System.Xml.Serialization;
- using TagLib.Id3v2;
-
- public static class DbUtil
- {
- public static void StoreDatabaseEntry (Tag tag, ISerializable dbEntry)
- {
- StringWriter data = new StringWriter (new StringBuilder ());
- XmlSerializer serializer = new XmlSerializer (dbEntry.GetType ());
- serializer.Serialize (data, dbEntry);
- PrivateFrame frame = PrivateFrame.Get (tag, "org.MyProgram.DatabaseEntry", true);
- frame.PrivateData = Encoding.UTF8.GetBytes (data.ToString ());
- }
-
- public static object GetDatabaseEntry (Tag tag, Type type)
- {
- PrivateFrame frame = PrivateFrame.Get (tag, "org.MyProgram.DatabaseEntry", false);
- if (frame == null)
- return null;
-
- XmlSerializer serializer = new XmlSerializer (type);
- return serializer.Deserialize (new MemoryStream (frame.PrivateData));
- }
- }
-
-
- #using <System.dll>
- #using <System.Xml.dll>
- #using <taglib-sharp.dll>
-
- using System;
- using System::IO;
- using System::Runtime::Serialization;
- using System::Text;
- using System::Xml::Serialization;
- using TagLib::Id3v2;
-
- public ref class DbUtil abstract sealed
- {
- public:
- static void StoreDatabaseEntry (Tag^ tag, ISerializable^ dbEntry)
- {
- StringWriter^ data = gcnew StringWriter (gcnew StringBuilder);
- XmlSerializer serializer = gcnew XmlSerializer (dbEntry->GetType ());
- serializer->Serialize (data, dbEntry);
- PrivateFrame frame = PrivateFrame::Get (tag, L"org.MyProgram.DatabaseEntry", true);
- frame.PrivateData = Encoding::UTF8->GetBytes (data->ToString ());
- }
-
- static Object^ GetDatabaseEntry (Tag^ tag, Type^ type)
- {
- PrivateFrame^ frame = PrivateFrame::Get (tag, L"org.MyProgram.DatabaseEntry", false);
- if (frame == null)
- return null;
-
- XmlSerializer serializer = gcnew XmlSerializer (type);
- return serializer->Deserialize (gcnew MemoryStream (frame->PrivateData));
- }
- }
-
-
- Imports System
- Imports System.IO
- Imports System.Runtime.Serialization
- Imports System.Text
- Imports System.Xml.Serialization
- Imports TagLib.Id3v2
-
- Public Shared Class DbUtil
- Public Shared Sub StoreDatabaseEntry (tag As Tag, dbEntry As ISerializable)
- Dim data As New StringWriter (New StringBuilder ())
- Dim serializer As New XmlSerializer (dbEntry.GetType ())
- serializer.Serialize (data, dbEntry)
- Dim frame As PrivateFrame = PrivateFrame.Get (tag, "org.MyProgram.DatabaseEntry", True)
- frame.PrivateData = Encoding.UTF8.GetBytes (data.ToString ())
- End Sub
-
- Public Shared Sub GetDatabaseEntry (tag As Tag, type As Type)
- Dim frame As PrivateFrame = PrivateFrame.Get (tag, "org.MyProgram.DatabaseEntry", False)
- If frame Is Nothing Then Return Nothing
-
- Dim serializer As XmlSerializer = New XmlSerializer (type)
- Return serializer.Deserialize (New MemoryStream (frame.PrivateData))
- End Sub
- End Class
-
-
- import System
- import System.IO
- import System.Runtime.Serialization
- import System.Text
- import System.Xml.Serialization
- import TagLib.Id3v2
-
- public static class DbUtil:
- static def StoreDatabaseEntry (tag as Tag, dbEntry as ISerializable):
- data as StringWriter = StringWriter (StringBuilder ())
- serializer as XmlSerializer = XmlSerializer (dbEntry.GetType ())
- serializer.Serialize (data, dbEntry)
- frame as PrivateFrame = PrivateFrame.Get (tag, "org.MyProgram.DatabaseEntry", true)
- frame.PrivateData = Encoding.UTF8.GetBytes (data.ToString ())
-
- static def GetDatabaseEntry (tag As Tag, type As Type):
- frame as PrivateFrame = PrivateFrame.Get (tag, "org.MyProgram.DatabaseEntry", false)
- if frame == null:
- return null
-
- serializer as XmlSerializer = XmlSerializer (type)
- return serializer.Deserialize (MemoryStream (frame.PrivateData))
-
- TextInformationFrame frame = TextInformationFrame.Get (myTag, "TPE1", true);
- /* Upper casing all the text: */
- string[] text = frame.Text;
- for (int i = 0; i < text.Length; i++)
- text [i] = text [i].ToUpper ();
- frame.Text = text;
-
- /* Replacing the value completely: */
- frame.Text = new string [] {"DJ Jazzy Jeff"};
- UrlLinkFrame frame = UrlLinkFrame.Get (myTag, "WCOP", true);
- /* Upper casing all the text: */
- string[] text = frame.Text;
- for (int i = 0; i < text.Length; i++)
- text [i] = text [i].ToUpper ();
- frame.Text = text;
-
- /* Replacing the value completely: */
- frame.Text = new string [] {"http://www.somewhere.com"};
- file.RemoveTags (file.TagTypes & ~file.TagTypesOnDisk);
- file.RemoveTags (file.TagTypes & ~file.TagTypesOnDisk);
- file.RemoveTags (file.TagTypes & ~file.TagTypesOnDisk);
-
- Codec.AddCodecProvider (delegate (ByteVector packet) {
- return packet.StartsWith ("Speex ") ? new MySpeexCodec () : null;
- });
-
- using TagLib;
-
- [SupportedMimeType("taglib/wv", "wv")]
- [SupportedMimeType("audio/x-wavpack")]
- public class MyFile : File {
- ...
- }
-
- using System;
- using TagLib;
-
- public class ExceptionTest
- {
- public static void Main ()
- {
- try {
- File file = File.Create ("myfile.flv"); // Not supported, YET!
- } catch (UnsupportedFormatException e) {
- Console.WriteLine ("That file format is not supported: {0}", e.ToString ());
- }
- }
- }
-
-
- #using <System.dll>
- #using <taglib-sharp.dll>
-
- using System;
- using TagLib;
-
- void main ()
- {
- try {
- File file = File::Create ("myfile.flv"); // Not supported, YET!
- } catch (UnsupportedFormatException^ e) {
- Console::WriteLine ("That file format is not supported: {0}", e);
- }
- }
-
-
- Imports System
- Imports TagLib
-
- Public Class ExceptionTest
- Public Shared Sub Main ()
- Try
- file As File = File.Create ("myfile.flv") ' Not supported, YET!
- Catch e As UnsupportedFormatException
- Console.WriteLine ("That file format is not supported: {0}", e.ToString ());
- End Try
- End Sub
- End Class
-
-
- import System
- import TagLib
-
- try:
- file As File = File.Create ("myfile.flv") # Not supported, YET!
- catch e as UnsupportedFormatException:
- Console.WriteLine ("That file format is not supported: {0}", e.ToString ());
-
- file.RemoveTags (file.TagTypes & ~file.TagTypesOnDisk);
-