Search code examples
c#7zip

Getting 7-Zip error - Unable to pass File-names with spaces to Process.Start() method


I need to pass .zip file location into files parameter in the below c# code.

If the file name DOES NOT CONTAIN spaces, everything is working fine. But, if the file name DOES CONTAIN spaces, it is throwing below error.

Cannot find archive

Below is my code: Can anybody please suggest me how can I solve this problem?

        static void UnzipToFolder(string zipPath, string extractPath, string[] files)
    {
        string zipLocation = ConfigurationManager.AppSettings["zipLocation"];            

        foreach (string file in files)
        {
            string sourceFileName = string.Empty;
            string destinationPath = string.Empty;
            var name = Path.GetFileNameWithoutExtension(file);
            sourceFileName = Path.Combine(zipPath, file);
            destinationPath = Path.Combine(extractPath, name);

            var processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = zipLocation;
            processStartInfo.Arguments = @"x " + sourceFileName + " -o" + destinationPath;
            processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            var process = Process.Start(processStartInfo);
            process.WaitForExit();
        }
    }

Solution

  • Add quotes around the file paths:

    processStartInfo.Arguments = "x \"" + sourceFileName + "\" -o \"" + destinationPath + "\"";
    

    Or for readability (with C# 6):

    processStartInfo.Arguments = $"x \"{sourceFileName}\" -o \"{destinationPath}\"";