Search code examples
c#asp.net-mvczipdotnetzip

How to remove guid from file name when creating zip file?


When user uploads multiple documents I am storing their files in my project like this:

 Guid id;
 id = Guid.NewGuid();
 string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
 Path.GetFileName(id + item.FileName));
 item.SaveAs(filePath);

So files are saved like this in my project:

  1. 1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt
  2. bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt

Now when creating zip files I am getting same name of this files when extracting zip files but I don't want guid in my file name after user downloads file.

However I have tried to remove guid from my file name but getting error System.IO.FileNotFoundException.

This is my code:

using (var zip = new ZipFile())
{
    var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
    string[] str1 = str .Split(',');
    foreach (var item in str1)
    {
        string filePath = Server.MapPath("~/Uploads/" + item.Substring(36));//as guid are of 36 digits
        zip.AddFile(filePath, "files");
    }
    zip.Save(memoryStream);//Getting error here
}

Solution

  • ZipFile is throwing an exception because it can't find the file on disk as you have given it a name of a file that does not exist (by doing a .Substring()). To make it work you would have to rename the file using File.Copy with your new file name and then give that same file name to Zip.AddFile().

      var orgFileName = "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt";
      var newFileName = orgFileName.Substring (36);
      File.Copy (orgFileName, newFileName, true);
      zip.AddFile (newFileName);