简体   繁体   中英

Invalid Characters in Path while Compression in C#

I am having a problem where I am trying to ZIP up a file using the below code :-

        Process msinfo = new Process();
        msinfo.StartInfo.FileName = "msinfo32.exe";
        string path = "\"" + Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\test.nfo" + "\"";
        string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\test.nfo";
        MessageBox.Show(path);
        msinfo.StartInfo.Arguments = @"/nfo "+path;
        //msinfo.Start();
        //msinfo.WaitForExit();
        //MessageBox.Show("The File Has Been Saved!");
        ZipFile.CreateFromDirectory(zippath, @"C:\Test.zip");
        MessageBox.Show("Everything Is Done!");

The error that is coming is that the Folder path is not valid. I also tried by including quotation marks in the Zippath variable but it did not work.

PS - My machine name has 3 words so it has got spaces as well. Help is appreciated ^_^

The first argument of ZipFile.CreateFromDirectory should be a path of a directory, not a file (test.nfo in this case). If you want compress the whole directory (eg the Desktop dir) then omit the "test.nfo" from the path, like this:

string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

If you want to create a zip archive from only one file then use the ZipFileExtensions.CreateEntryFromFile .

One more thing: when you want to build a path from two or more components use the Path.Combine method instead of simple string concatenation. It can spare you from a lot of pain (like adding path separator characters).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM