LoginSignup
1
6

More than 5 years have passed since last update.

Zipファイルの中身を書き換える

Posted at

zipファイルに含まれているテキストファイルの一部を書き換える必要があったので、プログラムを作成してみた。

C#のサンプルプログラム

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

class MyZipFile
{
    public static void Run()
    {
        string path = "Test.zip";
        string name = "Test.txt";
        using (ZipArchive a = ZipFile.Open(path, ZipArchiveMode.Update))
        {
            ZipArchiveEntry e = a.GetEntry(name);
            if (e == null)
            {
                Console.WriteLine("file not found, {0}", name);
                return;
            }
            StreamReader sr = new StreamReader(e.Open(), Encoding.GetEncoding("shift_jis"));
            string s0 = sr.ReadToEnd();
            sr.Dispose();

            string s1 = s0.Replace("Japanese", "English");

            StreamWriter sw = new StreamWriter(e.Open(), Encoding.GetEncoding("shift_jis"));
            sw.Write(s1);
            sw.Dispose();
        }
    }
}

PowerShellのサンプルプログラム

Add-Type -AssemblyName System.IO.Compression.FileSystem

using namespace System.IO; using namespace System.Text; using namespace System.IO.Compression

Class MyZipFile
{
    static [int] Run($path, $name)
    {
        if(!(Test-Path $path)) {
            Write-Host "zip file not found, $path"
            return 1
        }
        $a = [ZipFile]::Open($path, "Update")
        $e = $a.GetEntry($name)
        if($e -eq $null) {
            Write-Host "file not found, $name"
            $a.Dispose()
            return 1
        }

        $sr = New-Object StreamReader($e.Open(), [Encoding]::GetEncoding("shift_jis"))
        $s0 = $sr.ReadToEnd()
        $sr.Dispose()

        $s1 = $s0.Replace("Japanese", "English")

        $sw = New-Object StreamWriter($e.Open(), [Encoding]::GetEncoding("shift_jis"))
        $sw.Write($s1)
        $sw.Dispose()

        $a.Dispose()
        return 0
    }
}

$path = "Test.zip"
$name = "Test.txt"

$r = [MyZipFile]::Run($path, $name)

using namespaceを一行に記述しないと何故か最終行のみ有効となる。不具合かも。
OSはWindows 10 Home 64-bit。

PS C:\tools> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.15063.729
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.729
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
1
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
6