@@ -44,9 +44,19 @@ public static void AddNarToSfx(
4444 string tempFile = Path . GetTempFileName ( ) ;
4545 // 拡張子を .7z にしないと 7z.exe が形式を認識しない場合があるため改名
4646 string temp7z = tempFile + ".7z" ;
47- // アーカイブ内でのファイル名を initial_install.nar に固定するため、
48- // 元のファイル名に関わらず同名の一時ファイルにコピーしてから追加する
49- string tempNar = Path . Combine ( Path . GetTempPath ( ) , "initial_install.nar" ) ;
47+
48+ // アーカイブ内でのファイル名を initial_install.nar に固定するための準備。
49+ // データコピーを避けるため、ファイル名が異なる場合は同ディレクトリ内でリネームして追加し
50+ // finally で必ず元の名前に戻す。ただし同名ファイルが既に存在する場合は一時ディレクトリへの
51+ // コピーにフォールバックする。
52+ string narDir = Path . GetDirectoryName ( Path . GetFullPath ( narFilePath ) ) ;
53+ bool alreadyCorrectName = string . Equals (
54+ Path . GetFileName ( narFilePath ) , "initial_install.nar" ,
55+ StringComparison . OrdinalIgnoreCase ) ;
56+
57+ string narPathForArchive = null ;
58+ string narWorkDir = null ;
59+ string renamedOriginalPath = null ; // リネームした元のパス(finallyで戻すため)
5060 try
5161 {
5262 progress . Report ( "7zアーカイブ部分を一時ファイルに書き出し中..." ) ;
@@ -56,11 +66,29 @@ public static void AddNarToSfx(
5666 fs . Write ( inputBytes , sigOffset , inputBytes . Length - sigOffset ) ;
5767 }
5868
59- File . Copy ( narFilePath , tempNar , overwrite : true ) ;
69+ if ( alreadyCorrectName )
70+ {
71+ // ファイル名が既に initial_install.nar なのでそのまま使用
72+ narPathForArchive = narFilePath ;
73+ narWorkDir = narDir ;
74+ }
75+ else
76+ {
77+ string targetPath = Path . Combine ( narDir , "initial_install.nar" ) ;
78+ if ( File . Exists ( targetPath ) )
79+ throw new IOException (
80+ $ "リネーム先のファイルが既に存在します。削除してから再試行してください。\n { targetPath } ") ;
81+
82+ // 同ディレクトリ内でリネーム(データコピーなし)
83+ File . Move ( narFilePath , targetPath ) ;
84+ renamedOriginalPath = narFilePath ;
85+ narPathForArchive = targetPath ;
86+ narWorkDir = narDir ;
87+ }
6088
6189 progress . Report ( "initial_install.nar をアーカイブに追加中..." ) ;
62- // -w で作業ディレクトリを一時フォルダに指定し 、ファイル名のみがパスに使われるようにする
63- RunSevenZip ( sevenZipExe , $ "a \" { temp7z } \" \" { tempNar } \" -w\" { Path . GetTempPath ( ) } \" ", progress ) ;
90+ // -w で作業ディレクトリを指定し 、ファイル名のみがパスに使われるようにする
91+ RunSevenZip ( sevenZipExe , $ "a \" { temp7z } \" \" { narPathForArchive } \" -w\" { narWorkDir } \" ", progress ) ;
6492
6593 progress . Report ( $ "出力ファイルを書き込み中: { outputSfxPath } ") ;
6694 byte [ ] newArchiveBytes = File . ReadAllBytes ( temp7z ) ;
@@ -76,8 +104,9 @@ public static void AddNarToSfx(
76104 {
77105 if ( File . Exists ( temp7z ) )
78106 File . Delete ( temp7z ) ;
79- if ( File . Exists ( tempNar ) )
80- File . Delete ( tempNar ) ;
107+ // リネームしていた場合は元のファイル名に戻す
108+ if ( renamedOriginalPath != null && File . Exists ( narPathForArchive ) )
109+ File . Move ( narPathForArchive , renamedOriginalPath ) ;
81110 }
82111 }
83112
0 commit comments