【问题标题】:Powershell .NET System.IO.Compression to C# .NET Conversion [closed]Powershell .NET System.IO.Compression 到 C# .NET 的转换 [关闭]
【发布时间】:2014-07-21 17:18:33
【问题描述】:

我有以下在 powershell 中正常工作的内容,想知道如何在 C# 中做同样的事情。我需要找到 .zip 文件,并将它们一个一个解压缩到临时位置搜索内容,如果找到则列出文件,然后删除临时文件继续下一个。

我的问题是;能够完成解压缩、文件搜索和删除功能的相应 C# 方法是什么?

function Lookin-Zips() {
    param ($SearchPattern);
    $archive = [System.IO.Compression.ZipFile]::OpenRead($archivePath);
    try {
        # enumerate all entries in the archive, which includes both files and directories
        foreach($archiveEntry in $archive.Entries) {
            # if the entry is not a directory (which ends with /)
            if($archiveEntry.FullName -notmatch '/$') {
                # get temporary file -- note that this will also create the file
                $tempFile = [System.IO.Path]::GetTempFileName();
                try {
                    # extract to file system
                    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($archiveEntry, $tempFile, $true);

                    # create PowerShell backslash-friendly path from ZIP path with forward slashes
                    $windowsStyleArchiveEntryName = $archiveEntry.FullName.Replace('/', '\');
                    # run selection
                    Get-ChildItem $tempFile | Select-String -pattern "$SearchPattern" | Select-Object @{Name="Filename";Expression={$windowsStyleArchiveEntryName}}, @{Name="Path";Expression={Join-Path $archivePath (Split-Path $windowsStyleArchiveEntryName -Parent)}}, Matches, LineNumber
                }
                finally {
                    Remove-Item $tempFile;
                }
            }
        }
    }

    finally {
        # release archive object to prevent leaking resources
        $archive.Dispose();
    }
}

【问题讨论】:

  • 这个问题似乎跑题了,因为它要求的是代码翻译。

标签: c# powershell unzip file-search


【解决方案1】:

This is how you unzip your files in c#

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string startPath = @"c:\example\start";
            string zipPath = @"c:\example\result.zip";
            string extractPath = @"c:\example\extract";

            ZipFile.CreateFromDirectory(startPath, zipPath);

            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}

And you can use GetFiles method to list the matching file

public static string[] GetFiles(
    string path,
    string searchPattern
)

最后您可以使用File.DeleteDirectory.Delete 删除文件和目录。

【讨论】:

    猜你喜欢
    • 2011-08-20
    • 2011-01-03
    • 2011-07-27
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多