Compress a folder using NTFS compression in .NET

前端 未结 6 1229
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:16

    This is a slight adaption of Igal Serban answer. I ran into a subtle issue with the Name having to be in a very specific format. So I added some Replace("\\", @"\\").TrimEnd('\\') magic to normalize the path first, I also cleaned up the code a bit.

    var dir = new DirectoryInfo(_outputFolder);
    
    if (!dir.Exists)
    {
        dir.Create();
    }
    
    if ((dir.Attributes & FileAttributes.Compressed) == 0)
    {
        try
        {
            // Enable compression for the output folder
            // (this will save a ton of disk space)
    
            string objPath = "Win32_Directory.Name=" + "'" + dir.FullName.Replace("\\", @"\\").TrimEnd('\\') + "'";
    
            using (ManagementObject obj = new ManagementObject(objPath))
            {
                using (obj.InvokeMethod("Compress", null, null))
                {
                    // I don't really care about the return value, 
                    // if we enabled it great but it can also be done manually
                    // if really needed
                }
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine("Cannot enable compression for folder '" + dir.FullName + "': " + ex.Message, "WMI");
        }
    }
    

提交回复
热议问题