mercoledì 4 giugno 2014

Zipping files/folders and then delete the source.

C# .NET Framework 4.51

In my console application, I want to zip a single file or folder and then delete the source.
For this purpose, I use the ZipFile object for zipping folders and ZipArchive object for zipping files.
The problem is that after zip, I have an exception when I delete the source, because folders or files are in use, so I have resolved with asynchronous programming using a Task object (and arguments) with Async and Await.

private async void ExecuteCommand()
        {
// Arguments for async task.
var arguments = new List<string> {zipOutput, sourceName, internalOperation};

var returnedTask = DoTaskAsync(arguments);
bool taskResult = await returnedTask;

if (taskResult)
{
    if (internalOperation.Equals("folder"))
    {
        // Remove the read-only attribute.
        var di = new DirectoryInfo(destinationRepositoryName);

        foreach (var file in di.GetFiles("*", SearchOption.AllDirectories))
            file.Attributes &= ~FileAttributes.ReadOnly;

            Directory.Delete(sourceName, true);
     }
     else
         File.Delete(sourceName);

     Console.WriteLine(Environment.NewLine);
     Console.WriteLine("End zipping file -> " + zipOutput);
 }
}

// Signature specifies Task<TResult>
private async Task<bool> DoTaskAsync(IReadOnlyList<string> arguments)
{
    try
    {
         Console.WriteLine(Environment.NewLine);
         if (arguments != null)
         {
             Console.WriteLine("Create zipping file -> " + arguments[0]);
                   
             if (arguments[2].Equals("folder"))
                 ZipFile.CreateFromDirectory(arguments[1], arguments[0], CompressionLevel.Fastest, true);
             else
             {
                 using (var archive = ZipFile.Open(arguments[0], ZipArchiveMode.Create))
                 {
                     var fileInfo = new FileInfo(arguments[1]);
                     archive.CreateEntryFromFile(arguments[1], fileInfo.Name);
                 }
              }
              return true;
         }
         Console.WriteLine("Can't create zip file because arguments are null.");
               
         return false;
     }
     catch (Exception ex)
     {
         return false;
     }
 }

See you soon!