Files

89 lines
3.1 KiB
C#
Raw Permalink Normal View History

2025-09-12 09:02:03 -04:00
using System;
using System.IO;
2026-03-18 16:37:59 -04:00
namespace SabreTools.Wrappers
2025-09-12 09:02:03 -04:00
{
public partial class PFF : IExtractable
{
/// <inheritdoc/>
public bool Extract(string outputDirectory, bool includeDebug)
{
// If we have no segments
2026-01-25 14:30:18 -05:00
if (Segments is null || Segments.Length == 0)
2025-09-12 09:02:03 -04:00
return false;
// Loop through and extract all files to the output
bool allExtracted = true;
for (int i = 0; i < Segments.Length; i++)
{
allExtracted &= ExtractSegment(i, outputDirectory, includeDebug);
}
return allExtracted;
}
/// <summary>
/// Extract a segment from the PFF to an output directory by index
/// </summary>
/// <param name="index">Segment index to extract</param>
/// <param name="outputDirectory">Output directory to write to</param>
/// <param name="includeDebug">True to include debug data, false otherwise</param>
/// <returns>True if the segment extracted, false otherwise</returns>
public bool ExtractSegment(int index, string outputDirectory, bool includeDebug)
{
// If we have no files
if (FileCount == 0)
return false;
// If we have no segments
2026-01-25 14:30:18 -05:00
if (Segments is null || Segments.Length == 0)
2025-09-12 09:02:03 -04:00
return false;
// If we have an invalid index
if (index < 0 || index >= Segments.Length)
return false;
// Get the read index and length
var segment = Segments[index];
int offset = (int)segment.FileLocation;
int size = (int)segment.FileSize;
try
{
// Ensure directory separators are consistent
string filename = segment.FileName ?? $"file{index}";
filename = filename.TrimStart(['\\', '/']);
2025-09-12 09:02:03 -04:00
if (Path.DirectorySeparatorChar == '\\')
filename = filename.Replace('/', '\\');
else if (Path.DirectorySeparatorChar == '/')
filename = filename.Replace('\\', '/');
// Ensure the full output directory exists
filename = Path.Combine(outputDirectory, filename);
var directoryName = Path.GetDirectoryName(filename);
2026-01-25 14:32:49 -05:00
if (directoryName is not null && !Directory.Exists(directoryName))
2025-09-12 09:02:03 -04:00
Directory.CreateDirectory(directoryName);
// Create the output file
using var fs = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.None);
2025-09-12 09:02:03 -04:00
// Read the data block
var data = ReadRangeFromSource(offset, size);
2025-09-20 09:49:42 -04:00
if (data.Length == 0)
2025-09-12 09:02:03 -04:00
return false;
// Write the data -- TODO: Compressed data?
fs.Write(data, 0, size);
fs.Flush();
return true;
}
catch (Exception ex)
{
if (includeDebug) Console.Error.WriteLine(ex);
return false;
}
}
}
}