diff --git a/Services/FastDirectorySnapshot.cs b/Services/FastDirectorySnapshot.cs
index f54a604..acf95e6 100644
--- a/Services/FastDirectorySnapshot.cs
+++ b/Services/FastDirectorySnapshot.cs
@@ -145,6 +145,47 @@ namespace GameLauncher.Services
.Select(f => Path.Combine(normalized, f))
.ToArray();
}
+
+ ///
+ /// 別のスナップショットの内容を現在のスナップショットにマージします。
+ ///
+ /// マージ元のスナップショット
+ public void MergeFrom(FastDirectorySnapshot other)
+ {
+ if (other == null) return;
+
+ foreach (var kvp in other.FilesByDir)
+ {
+ if (!this.FilesByDir.TryGetValue(kvp.Key, out var files))
+ {
+ files = new HashSet(kvp.Value, StringComparer.OrdinalIgnoreCase);
+ this.FilesByDir[kvp.Key] = files;
+ }
+ else
+ {
+ files.UnionWith(kvp.Value);
+ }
+ }
+
+ foreach (var kvp in other.SubDirsByDir)
+ {
+ if (!this.SubDirsByDir.TryGetValue(kvp.Key, out var subDirs))
+ {
+ subDirs = new List(kvp.Value);
+ this.SubDirsByDir[kvp.Key] = subDirs;
+ }
+ else
+ {
+ foreach (var dir in kvp.Value)
+ {
+ if (!subDirs.Contains(dir, StringComparer.OrdinalIgnoreCase))
+ {
+ subDirs.Add(dir);
+ }
+ }
+ }
+ }
+ }
#endregion
#region □メソッド(Private)
diff --git a/Services/GameScannerService.cs b/Services/GameScannerService.cs
index 3ef1add..97539e5 100644
--- a/Services/GameScannerService.cs
+++ b/Services/GameScannerService.cs
@@ -610,26 +610,39 @@ namespace GameLauncher.Services
await Task.Run(() =>
{
var copyList = games.ToList();
- bool cacheNeedsSave = false;
+ int cacheNeedsSave = 0;
int total = copyList.Count;
int processed = 0;
- foreach (var game in copyList)
+ var po = new ParallelOptions
{
- processed++;
- if (onProgress != null && (processed % 5 == 0 || processed == total))
+ CancellationToken = ct,
+ MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 2, 4, 16)
+ };
+
+ try
+ {
+ Parallel.ForEach(copyList, po, (game, loopState) =>
{
- onProgress(processed, total, $"実在検証中... ({processed}/{total})");
- }
- if (ct.IsCancellationRequested) break;
+ if (ct.IsCancellationRequested)
+ {
+ loopState.Stop();
+ return;
+ }
+
+ int current = Interlocked.Increment(ref processed);
+ if (onProgress != null && (current % 10 == 0 || current == total))
+ {
+ onProgress(current, total, $"実在検証中... ({current}/{total})");
+ }
// 実在検証
if (!Directory.Exists(game.RootDirectory))
{
onGameRemoved(game);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
if (game is UnityGameItem ug)
@@ -640,13 +653,13 @@ namespace GameLauncher.Services
if (!string.IsNullOrEmpty(recovered))
{
ug.ExecutablePath = recovered;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
{
onGameRemoved(ug);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
}
@@ -656,7 +669,7 @@ namespace GameLauncher.Services
try
{
ug.FolderLastModified = Directory.GetLastWriteTime(ug.RootDirectory);
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
catch { }
}
@@ -666,7 +679,7 @@ namespace GameLauncher.Services
if (ug.HasSaveData != hasSave)
{
ug.HasSaveData = hasSave;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
// アイコン読み込み
@@ -692,7 +705,7 @@ namespace GameLauncher.Services
tg.RgssArchivePath = null;
tg.PluginsJsPath = string.Empty;
tg.PluginsDirPath = string.Empty;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
@@ -704,7 +717,7 @@ namespace GameLauncher.Services
FixRgssTitleFromIni(tg);
if (tg.Title != oldTitle)
{
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
}
@@ -727,7 +740,7 @@ namespace GameLauncher.Services
{
tg.EvbExtractedDirPath = currentEvbOutDir;
}
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
@@ -740,13 +753,13 @@ namespace GameLauncher.Services
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
{
onGameRemoved(tg);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
}
@@ -763,7 +776,7 @@ namespace GameLauncher.Services
tg.IsWolfExtracted = isWolfExtracted;
tg.WolfProxyDll = isProxyDll;
tg.IsModded = isProxyDll;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
}
else if (tg.IsSrpgStudio)
@@ -774,13 +787,13 @@ namespace GameLauncher.Services
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
{
onGameRemoved(tg);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
}
@@ -797,7 +810,7 @@ namespace GameLauncher.Services
tg.IsSrpgExtracted = isSrpgExtracted;
tg.SrpgProxyDll = isProxyDll;
tg.IsModded = isProxyDll || isModScript;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
}
else if (tg.IsAsar)
@@ -808,8 +821,8 @@ namespace GameLauncher.Services
if (!asarExists)
{
onGameRemoved(tg);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
// 解凍状態の整合性確認
@@ -819,13 +832,13 @@ namespace GameLauncher.Services
if (tg.IsAsarExtracted && (!dirExtracted || !jsExists))
{
tg.IsAsarExtracted = false;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
else if (!tg.IsAsarExtracted && dirExtracted && jsExists)
{
tg.IsAsarExtracted = true;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
}
@@ -837,14 +850,14 @@ namespace GameLauncher.Services
if (!archiveExists && !scriptExists)
{
onGameRemoved(tg);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
if (tg.IsRgssExtracted != scriptExists)
{
tg.IsRgssExtracted = scriptExists;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
}
@@ -853,8 +866,8 @@ namespace GameLauncher.Services
if (!File.Exists(tg.ExecutablePath) && !File.Exists(Path.Combine(tg.RootDirectory, "package.json")))
{
onGameRemoved(tg);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
}
else if (tg.IsEvbPacked || tg.IsStandaloneExePackage || tg.IsOther)
@@ -865,13 +878,13 @@ namespace GameLauncher.Services
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
{
onGameRemoved(tg);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
}
}
@@ -880,8 +893,8 @@ namespace GameLauncher.Services
if (!File.Exists(tg.PluginsJsPath))
{
onGameRemoved(tg);
- cacheNeedsSave = true;
- continue;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
+ return;
}
}
@@ -891,7 +904,7 @@ namespace GameLauncher.Services
try
{
tg.FolderLastModified = Directory.GetLastWriteTime(tg.RootDirectory);
- cacheNeedsSave = true;
+ Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
catch { }
@@ -933,9 +946,13 @@ namespace GameLauncher.Services
}
}
}
+ });
+ }
+ catch (OperationCanceledException)
+ {
}
- if (cacheNeedsSave)
+ if (cacheNeedsSave != 0)
{
this.SaveCache(copyList.Where(g => Directory.Exists(g.RootDirectory)));
}
@@ -960,7 +977,7 @@ namespace GameLauncher.Services
var po = new ParallelOptions
{
CancellationToken = ct,
- MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 2, 4, 16)
+ MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 4, 8, 32)
};
// 1. Everything / NTFS MFT による超高速スナップショット取得
@@ -1020,32 +1037,37 @@ namespace GameLauncher.Services
onLogMessage?.Invoke("標準の並列ディレクトリ走査を実行します。");
}
+ // 全ターゲットディレクトリの直下サブディレクトリを一括集約(複数ドライブのI/Oを完全並列化)
+ var allSubDirs = new List();
foreach (var targetPath in targetPaths)
{
if (ct.IsCancellationRequested) break;
if (!Directory.Exists(targetPath)) continue;
- onStatusUpdated?.Invoke($"新規フォルダ走査中: {Path.GetFileName(targetPath.TrimEnd('\\', '/'))}...");
- List subDirs;
try
{
if (snapshot != null && snapshot.DirectoryExists(targetPath))
{
- subDirs = [.. snapshot.GetDirectories(targetPath)];
+ allSubDirs.AddRange(snapshot.GetDirectories(targetPath));
}
else
{
- subDirs = [.. Directory.EnumerateDirectories(targetPath)];
+ allSubDirs.AddRange(Directory.EnumerateDirectories(targetPath));
}
}
catch
{
continue;
}
+ }
+
+ if (allSubDirs.Count > 0)
+ {
+ onStatusUpdated?.Invoke($"新規フォルダ走査中 ({allSubDirs.Count} フォルダ)... (並列度 {po.MaxDegreeOfParallelism})");
try
{
- Parallel.ForEach(subDirs, po, (dir, loopState) =>
+ Parallel.ForEach(allSubDirs, po, (dir, loopState) =>
{
if (ct.IsCancellationRequested)
{
@@ -1118,7 +1140,6 @@ namespace GameLauncher.Services
}
catch (OperationCanceledException)
{
- break;
}
}
}, ct);
diff --git a/Services/NtfsMftScanService.cs b/Services/NtfsMftScanService.cs
index 02d2a33..d2aba19 100644
--- a/Services/NtfsMftScanService.cs
+++ b/Services/NtfsMftScanService.cs
@@ -1,8 +1,11 @@
using System;
+using System.Buffers.Binary;
+using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
+using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace GameLauncher.Services
@@ -21,6 +24,11 @@ namespace GameLauncher.Services
private const uint FSCTL_QUERY_USN_JOURNAL = 0x000900f4;
private const uint FSCTL_ENUM_USN_DATA = 0x000900b3;
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
+
+ ///
+ /// MFT読み込みバッファサイズ(2MB)。1回のDeviceIoControl呼び出しで最大効率を引き出します。
+ ///
+ private const int BufferSize = 2048 * 1024;
#endregion
#region □構造体(Private)
@@ -44,24 +52,26 @@ namespace GameLauncher.Services
public long HighUsn;
}
- private class MftNode
+ ///
+ /// MFTディレクトリ情報ノード
+ ///
+ private struct DirNode
{
public ulong Id;
public ulong ParentId;
- public string Name = string.Empty;
- public bool IsDirectory;
+ public string Name;
}
#endregion
#region □メソッド(Public)
///
/// 指定されたパス群(例: C:\..., Z:\...)に対して、NTFS MFT 直接読み取りを用いて高速スナップショットを生成します。
+ /// 複数ドライブが存在する場合は、各ドライブを並列処理してディスクアクセス速度を極限まで高めます。
///
/// 走査対象のディレクトリルート一覧
/// 生成されたスナップショット。失敗または非NTFS時は null
public static FastDirectorySnapshot? TryScanTargetsFast(IEnumerable targetDirectories)
{
- var snapshot = new FastDirectorySnapshot();
var targetsByDrive = new Dictionary>();
foreach (var dir in targetDirectories)
@@ -82,34 +92,44 @@ namespace GameLauncher.Services
if (targetsByDrive.Count == 0) return null;
- bool anySuccess = false;
+ var snapshots = new ConcurrentBag();
- foreach (var kvp in targetsByDrive)
+ // ドライブごとに並列処理を実行(物理/論理ドライブ間のI/OおよびCPUを限界まで同時並行化)
+ Parallel.ForEach(targetsByDrive, kvp =>
{
char driveLetter = kvp.Key;
var targetPaths = kvp.Value;
+ var driveSnapshot = new FastDirectorySnapshot();
try
{
- bool ok = ScanVolumeMft(driveLetter, targetPaths, snapshot);
- if (ok)
+ bool ok = ScanVolumeMft(driveLetter, targetPaths, driveSnapshot);
+ if (ok && (driveSnapshot.TotalDirectoryCount > 0 || driveSnapshot.TotalFileCount > 0))
{
- anySuccess = true;
+ snapshots.Add(driveSnapshot);
}
}
catch
{
// ドライブスキャン失敗時はスキップ
}
+ });
+
+ if (snapshots.IsEmpty) return null;
+
+ var merged = new FastDirectorySnapshot();
+ foreach (var snap in snapshots)
+ {
+ merged.MergeFrom(snap);
}
- return anySuccess ? snapshot : null;
+ return merged;
}
#endregion
#region □メソッド(Private)
///
- /// 1つのドライブボリュームのMFTを読み込み、指定されたパス配下のファイルをスナップショットに登録します。
+ /// 1つのドライブボリュームのMFTを読み込み、指定されたターゲットパス配下のファイルをスナップショットに登録します。
///
private static bool ScanVolumeMft(char driveLetter, List targetPaths, FastDirectorySnapshot snapshot)
{
@@ -148,17 +168,16 @@ namespace GameLauncher.Services
IntPtr enumDataPtr = Marshal.AllocHGlobal(enumDataSize);
Marshal.StructureToPtr(enumData, enumDataPtr, false);
- const int bufferSize = 1024 * 512; // 512KBバッファ
- byte[] buffer = new byte[bufferSize];
+ byte[] buffer = new byte[BufferSize];
GCHandle bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject();
- // ID -> MftNode のマッピングを保持
- var nodes = new Dictionary(500000);
+ // 読み込んだ全MFTデータチャンクを保持(I/Oを最優先で一括連続完了させる)
+ var chunks = new List<(byte[] Buffer, int Length)>();
try
{
- while (DeviceIoControl(hVolume, FSCTL_ENUM_USN_DATA, enumDataPtr, enumDataSize, bufferPtr, bufferSize, out uint bytesReturned, IntPtr.Zero))
+ while (DeviceIoControl(hVolume, FSCTL_ENUM_USN_DATA, enumDataPtr, enumDataSize, bufferPtr, BufferSize, out uint bytesReturned, IntPtr.Zero))
{
if (bytesReturned <= 8) break;
@@ -166,36 +185,9 @@ namespace GameLauncher.Services
ulong nextId = (ulong)Marshal.ReadInt64(bufferPtr);
Marshal.WriteInt64(enumDataPtr, (long)nextId);
- int offset = 8;
- while (offset < bytesReturned)
- {
- IntPtr recordPtr = IntPtr.Add(bufferPtr, offset);
- int recordLength = Marshal.ReadInt32(recordPtr);
- if (recordLength <= 0) break;
-
- ulong fileRef = (ulong)Marshal.ReadInt64(recordPtr, 8) & 0x0000FFFFFFFFFFFFUL;
- ulong parentRef = (ulong)Marshal.ReadInt64(recordPtr, 16) & 0x0000FFFFFFFFFFFFUL;
- uint fileAttributes = (uint)Marshal.ReadInt32(recordPtr, 52);
- int fileNameLength = Marshal.ReadInt16(recordPtr, 56);
- int fileNameOffset = Marshal.ReadInt16(recordPtr, 58);
-
- if (fileNameLength > 0)
- {
- string fileName = Marshal.PtrToStringUni(IntPtr.Add(recordPtr, fileNameOffset), fileNameLength / 2);
- bool isDir = (fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
-
- var node = new MftNode
- {
- Id = fileRef,
- ParentId = parentRef,
- Name = fileName,
- IsDirectory = isDir
- };
- nodes[fileRef] = node;
- }
-
- offset += recordLength;
- }
+ byte[] chunkCopy = new byte[bytesReturned];
+ Buffer.BlockCopy(buffer, 0, chunkCopy, 0, (int)bytesReturned);
+ chunks.Add((chunkCopy, (int)bytesReturned));
}
}
finally
@@ -204,27 +196,99 @@ namespace GameLauncher.Services
if (enumDataPtr != IntPtr.Zero) Marshal.FreeHGlobal(enumDataPtr);
}
- if (nodes.Count == 0) return false;
+ if (chunks.Count == 0) return false;
- // 3. 親IDから子IDのツリーを構築
- var childrenByParent = new Dictionary>(nodes.Count);
- foreach (var node in nodes.Values)
+ // 3. 【第1パス】ディレクトリのみを収集(ディレクトリは全体の数%に過ぎないため極めて高速)
+ var dirNodes = new Dictionary(65536);
+ var childrenByParent = new Dictionary>(65536);
+
+ foreach (var chunk in chunks)
{
- if (!childrenByParent.TryGetValue(node.ParentId, out var list))
+ ReadOnlySpan span = chunk.Buffer.AsSpan(0, chunk.Length);
+ int offset = 8;
+ while (offset < chunk.Length)
{
- list = new List();
- childrenByParent[node.ParentId] = list;
+ if (offset + 60 > chunk.Length) break;
+ ReadOnlySpan record = span.Slice(offset);
+ int recordLength = BinaryPrimitives.ReadInt32LittleEndian(record);
+ if (recordLength <= 0 || offset + recordLength > chunk.Length) break;
+
+ uint fileAttributes = BinaryPrimitives.ReadUInt32LittleEndian(record.Slice(52));
+ if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
+ {
+ ulong fileRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(8)) & 0x0000FFFFFFFFFFFFUL;
+ ulong parentRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(16)) & 0x0000FFFFFFFFFFFFUL;
+ ushort fileNameLength = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(56));
+ ushort fileNameOffset = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(58));
+
+ if (fileNameLength > 0 && fileNameOffset + fileNameLength <= recordLength)
+ {
+ string dirName = Encoding.Unicode.GetString(record.Slice(fileNameOffset, fileNameLength));
+ dirNodes[fileRef] = new DirNode { Id = fileRef, ParentId = parentRef, Name = dirName };
+
+ if (!childrenByParent.TryGetValue(parentRef, out var childList))
+ {
+ childList = new List();
+ childrenByParent[parentRef] = childList;
+ }
+ childList.Add(fileRef);
+ }
+ }
+
+ offset += recordLength;
}
- list.Add(node.Id);
}
- // 4. 各ターゲットパスのノードIDを特定し、その配下のエントリをスナップショットに格納
+ // 4. ターゲットパスのNodeId特定と、配下の子孫ディレクトリパスの確定
+ var targetDirIds = new HashSet();
+ var dirIdToFullPath = new Dictionary();
+
foreach (var targetPath in targetPaths)
{
- var targetNodeId = FindNodeIdByPath(driveLetter, targetPath, nodes, childrenByParent);
+ ulong? targetNodeId = FindDirNodeIdByPath(driveLetter, targetPath, dirNodes, childrenByParent);
if (targetNodeId.HasValue)
{
- PopulateSnapshotFromNode(targetNodeId.Value, targetPath, nodes, childrenByParent, snapshot);
+ CollectDescendantDirectories(targetNodeId.Value, targetPath, dirNodes, childrenByParent, targetDirIds, dirIdToFullPath, snapshot);
+ }
+ }
+
+ // 該当するターゲットディレクトリが存在しなければ終了
+ if (targetDirIds.Count == 0) return true;
+
+ // 5. 【第2パス】ターゲット配下のファイルのみを高速抽出
+ // (ターゲット外の数百万個の無関係なファイルは名前取得やオブジェクト生成を完全にスキップ!)
+ foreach (var chunk in chunks)
+ {
+ ReadOnlySpan span = chunk.Buffer.AsSpan(0, chunk.Length);
+ int offset = 8;
+ while (offset < chunk.Length)
+ {
+ if (offset + 60 > chunk.Length) break;
+ ReadOnlySpan record = span.Slice(offset);
+ int recordLength = BinaryPrimitives.ReadInt32LittleEndian(record);
+ if (recordLength <= 0 || offset + recordLength > chunk.Length) break;
+
+ uint fileAttributes = BinaryPrimitives.ReadUInt32LittleEndian(record.Slice(52));
+ // ディレクトリは第1パスですでに登録済みのためスキップ
+ if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
+ {
+ ulong parentRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(16)) & 0x0000FFFFFFFFFFFFUL;
+
+ // ターゲット配下のディレクトリに属するファイルのみを抽出
+ if (targetDirIds.Contains(parentRef) && dirIdToFullPath.TryGetValue(parentRef, out string? parentDirPath))
+ {
+ ushort fileNameLength = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(56));
+ ushort fileNameOffset = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(58));
+
+ if (fileNameLength > 0 && fileNameOffset + fileNameLength <= recordLength)
+ {
+ string fileName = Encoding.Unicode.GetString(record.Slice(fileNameOffset, fileNameLength));
+ snapshot.AddFile(parentDirPath, fileName);
+ }
+ }
+ }
+
+ offset += recordLength;
}
}
@@ -232,19 +296,22 @@ namespace GameLauncher.Services
}
///
- /// パス文字列から対応するノードIDを検索します。
+ /// パス文字列から対応するディレクトリのノードIDを特定します。
///
- private static ulong? FindNodeIdByPath(char driveLetter, string path, Dictionary nodes, Dictionary> childrenByParent)
+ private static ulong? FindDirNodeIdByPath(
+ char driveLetter,
+ string path,
+ Dictionary dirNodes,
+ Dictionary> childrenByParent)
{
string rootStr = driveLetter + @":\";
if (path.Equals(rootStr.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase) || path.Equals(rootStr, StringComparison.OrdinalIgnoreCase))
{
- // ドライブ直下のルートディレクトリ(通常IDは 5 / 0x0005)
- return 5UL;
+ return 5UL; // ルートディレクトリID
}
var parts = path.Substring(3).Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
- ulong currentParent = 5UL; // ルートID
+ ulong currentParent = 5UL;
foreach (var part in parts)
{
@@ -253,7 +320,7 @@ namespace GameLauncher.Services
{
foreach (var childId in childIds)
{
- if (nodes.TryGetValue(childId, out var node) && node.IsDirectory && string.Equals(node.Name, part, StringComparison.OrdinalIgnoreCase))
+ if (dirNodes.TryGetValue(childId, out var node) && string.Equals(node.Name, part, StringComparison.OrdinalIgnoreCase))
{
currentParent = node.Id;
found = true;
@@ -268,31 +335,29 @@ namespace GameLauncher.Services
}
///
- /// ノードIDから配下を再帰的に巡回し、スナップショットに登録します。
+ /// ターゲットディレクトリ配下の子孫ディレクトリIDおよびフルパスを再帰的に収集し、スナップショットに登録します。
///
- private static void PopulateSnapshotFromNode(
+ private static void CollectDescendantDirectories(
ulong parentNodeId,
string currentPath,
- Dictionary nodes,
+ Dictionary dirNodes,
Dictionary> childrenByParent,
+ HashSet targetDirIds,
+ Dictionary dirIdToFullPath,
FastDirectorySnapshot snapshot)
{
+ targetDirIds.Add(parentNodeId);
+ dirIdToFullPath[parentNodeId] = currentPath;
+
if (!childrenByParent.TryGetValue(parentNodeId, out var childIds)) return;
foreach (var childId in childIds)
{
- if (!nodes.TryGetValue(childId, out var childNode)) continue;
+ if (!dirNodes.TryGetValue(childId, out var childNode)) continue;
- if (childNode.IsDirectory)
- {
- string childPath = Path.Combine(currentPath, childNode.Name);
- snapshot.AddDirectory(currentPath, childPath);
- PopulateSnapshotFromNode(childId, childPath, nodes, childrenByParent, snapshot);
- }
- else
- {
- snapshot.AddFile(currentPath, childNode.Name);
- }
+ string childPath = Path.Combine(currentPath, childNode.Name);
+ snapshot.AddDirectory(currentPath, childPath);
+ CollectDescendantDirectories(childId, childPath, dirNodes, childrenByParent, targetDirIds, dirIdToFullPath, snapshot);
}
}
#endregion