public async Task SaveIndexFile(IndexFile index, bool alreadySemaphoreLocked = false) { var index1Path = Path.Combine(_gameDirectory.FullName, $"{index.DataFile.GetDataFileName()}{IndexExtension}"); var index2Path = Path.Combine(_gameDirectory.FullName, $"{index.DataFile.GetDataFileName()}{Index2Extension}"); if (!alreadySemaphoreLocked) { await _semaphoreSlim.WaitAsync(); } try { if (IsIndexLocked(index.DataFile)) { throw new Exception("Cannot write index files; files current in use."); } BinaryWriter index1Stream = null; BinaryWriter index2Stream = null; try { try { index1Stream = new BinaryWriter(File.OpenWrite(index1Path)); index2Stream = new BinaryWriter(File.OpenWrite(index2Path)); } catch { index1Stream?.Dispose(); index2Stream?.Dispose(); // Set a minor delay and try again, in case the user has some sort of locking issue. await Task.Delay(200); index1Stream = new BinaryWriter(File.OpenWrite(index1Path)); index2Stream = new BinaryWriter(File.OpenWrite(index2Path)); } index.Save(index1Stream, index2Stream); } finally { index1Stream?.Dispose(); index2Stream?.Dispose(); } var _dat = new Dat(XivCache.GameInfo.GameDirectory); var largestDatNum = _dat.GetLargestDatNumber(index.DataFile); UpdateIndexDatCount(index.DataFile, largestDatNum, true); } finally { if (!alreadySemaphoreLocked) { _semaphoreSlim.Release(); } } }