Compress a folder using NTFS compression in .NET

前端 未结 6 1227
Happy的楠姐
Happy的楠姐 2021-02-01 09:48

I want to compress a folder using NTFS compression in .NET. I found this post, but it does not work. It throws an exception (\"Invalid Parameter\").

DirectoryI         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 10:13

    I have tested the code and it alt text!

    • Make sure it works for you with the gui. Maybe the allocation unit size is too big for compression. Or you don't have sufficient permissions.
    • For your destination use format like so: "c:/temp/testcomp" with forward slashes.

    Full code:

    using System.IO;
    using System.Management;
    
    class Program
    {
        static void Main(string[] args)
        {
            string destinationDir = "c:/temp/testcomp";
            DirectoryInfo directoryInfo = new DirectoryInfo(destinationDir);
            if ((directoryInfo.Attributes & FileAttributes.Compressed) != FileAttributes.Compressed)
            {
                string objPath = "Win32_Directory.Name=" + "\"" + destinationDir + "\"";
                using (ManagementObject dir = new ManagementObject(objPath))
                {
                    ManagementBaseObject outParams = dir.InvokeMethod("Compress", null, null);
                    uint ret = (uint)(outParams.Properties["ReturnValue"].Value);
                }
            }
         }
    }
    

提交回复
热议问题