Files
SabreTools/SabreTools.FileTypes/Folder.cs

365 lines
12 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using SabreTools.Core.Tools;
using SabreTools.Hashing;
2020-12-07 15:08:57 -08:00
using SabreTools.IO;
2024-04-24 13:45:38 -04:00
using SabreTools.IO.Extensions;
2024-10-24 00:36:44 -04:00
using SabreTools.IO.Logging;
2020-12-08 14:53:49 -08:00
namespace SabreTools.FileTypes
{
/// <summary>
/// Represents a folder for reading and writing
/// </summary>
2025-01-04 22:10:52 -05:00
public class Folder : BaseFile, IParent
{
#region Protected instance variables
/// <summary>
/// Hashes that are available for children
/// </summary>
protected HashType[] _hashTypes = [HashType.CRC32, HashType.MD5, HashType.SHA1];
/// <summary>
/// Set of children file objects
/// </summary>
2024-02-28 19:19:50 -05:00
protected List<BaseFile>? _children;
/// <summary>
/// Logging object
/// </summary>
protected Logger _logger;
2020-08-28 20:46:12 -07:00
/// <summary>
/// Flag specific to Folder to omit Machine name from output path
/// </summary>
2025-01-04 20:24:56 -05:00
private readonly bool _writeToParent;
#endregion
#region Constructors
/// <summary>
2025-01-04 20:24:56 -05:00
/// Create a new Folder with no base file
/// </summary>
2020-08-28 20:46:12 -07:00
/// <param name="writeToParent">True to write directly to parent, false otherwise</param>
public Folder(bool writeToParent = false) : base()
{
2024-10-19 23:17:37 -04:00
_writeToParent = writeToParent;
_logger = new Logger(this);
}
/// <summary>
2025-01-04 20:24:56 -05:00
/// Create a new Folder from the given file
/// </summary>
2025-01-04 20:24:56 -05:00
/// <param name="filename">Name of the folder to use</param>
/// <param name="writeToParent">True to write directly to parent, false otherwise</param>
public Folder(string filename, bool writeToParent = false) : base(filename)
{
2025-01-04 20:24:56 -05:00
_writeToParent = writeToParent;
_logger = new Logger(this);
}
#endregion
#region Extraction
/// <inheritdoc/>
public bool CopyAll(string outDir)
{
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return false;
// Copy all files from the current folder to the output directory recursively
try
{
// Make sure the folders exist
2024-10-19 23:17:37 -04:00
Directory.CreateDirectory(Filename);
Directory.CreateDirectory(outDir);
2024-10-19 23:17:37 -04:00
DirectoryCopy(Filename, outDir, true);
}
catch (Exception ex)
{
_logger.Error(ex);
return false;
}
return true;
}
// https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
/// <inheritdoc/>
public string? CopyToFile(string entryName, string outDir)
{
2024-02-28 19:19:50 -05:00
string? realentry = null;
2024-02-28 21:59:13 -05:00
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return null;
// Copy single file from the current folder to the output directory, if exists
try
{
// Make sure the folders exist
2024-10-19 23:17:37 -04:00
Directory.CreateDirectory(Filename);
Directory.CreateDirectory(outDir);
// Get all files from the input directory
2024-10-19 23:17:37 -04:00
List<string> files = PathTool.GetFilesOrdered(Filename);
// Now sort through to find the first file that matches
2024-11-12 21:12:06 -05:00
string? match = files.Find(s => s.EndsWith(entryName));
// If we had a file, copy that over to the new name
2024-02-28 21:59:13 -05:00
if (!string.IsNullOrEmpty(match))
{
realentry = match;
File.Copy(match, Path.Combine(outDir, entryName));
}
}
catch (Exception ex)
{
_logger.Error(ex);
return realentry;
}
return realentry;
}
/// <inheritdoc/>
public (Stream?, string?) GetEntryStream(string entryName)
{
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return (null, null);
// Copy single file from the current folder to the output directory, if exists
try
{
// Make sure the folders exist
2024-10-19 23:17:37 -04:00
Directory.CreateDirectory(Filename);
// Get all files from the input directory
2024-10-19 23:17:37 -04:00
List<string> files = PathTool.GetFilesOrdered(Filename);
// Now sort through to find the first file that matches
2024-11-12 21:12:06 -05:00
string? match = files.Find(s => s.EndsWith(entryName));
2024-07-16 14:58:04 -04:00
// If we had a file, open and return the stream
2024-02-28 21:59:13 -05:00
if (!string.IsNullOrEmpty(match))
{
Stream stream = File.Open(match, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
2024-07-16 14:58:04 -04:00
return (stream, match);
}
2024-07-16 14:58:04 -04:00
return (null, null);
}
catch (Exception ex)
{
_logger.Error(ex);
2024-07-16 14:58:04 -04:00
return (null, null);
}
}
#endregion
#region Information
/// <summary>
/// Set the hash type that can be included in children
/// </summary>
public void SetHashType(HashType hashType)
=> SetHashTypes([hashType]);
/// <summary>
/// Set the hash types that can be included in children
/// </summary>
public void SetHashTypes(HashType[] hashTypes)
=> _hashTypes = hashTypes;
/// <inheritdoc/>
public List<BaseFile>? GetChildren()
{
2024-02-28 19:19:50 -05:00
// If we have an invalid filename
2024-10-19 23:17:37 -04:00
if (Filename == null)
2024-02-28 19:19:50 -05:00
return null;
2025-01-06 10:33:13 -05:00
// If we already have children
if (_children != null && _children.Count > 0)
return _children;
// Build the child item list
_children = [];
foreach (string file in IOExtensions.SafeEnumerateFiles(Filename, "*", SearchOption.TopDirectoryOnly))
{
2025-01-06 10:33:13 -05:00
BaseFile? nf = FileTypeTool.GetInfo(file, _hashTypes);
if (nf != null)
_children.Add(nf);
}
2025-01-06 10:33:13 -05:00
foreach (string dir in IOExtensions.SafeEnumerateDirectories(Filename, "*", SearchOption.TopDirectoryOnly))
{
var fl = new Folder(dir);
_children.Add(fl);
}
return _children;
}
/// <inheritdoc/>
public List<string>? GetEmptyFolders()
{
2024-10-19 23:17:37 -04:00
return Filename.ListEmpty();
}
#endregion
#region Writing
/// <inheritdoc/>
2025-01-05 20:48:51 -05:00
public bool Write(string file, string outDir, BaseFile? baseFile)
{
2025-01-05 20:48:51 -05:00
// Check that the input file exists
if (!File.Exists(file))
{
_logger.Warning($"File '{file}' does not exist!");
return false;
}
file = Path.GetFullPath(file);
// Get the file stream for the file and write out
using Stream inputStream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return Write(inputStream, outDir, baseFile);
}
/// <inheritdoc/>
2025-01-05 20:49:34 -05:00
public bool Write(Stream? stream, string outDir, BaseFile? baseFile)
{
// If either input is null or empty, return
2025-01-05 20:49:34 -05:00
if (stream == null || baseFile == null || baseFile.Filename == null)
2024-07-17 15:19:15 -04:00
return false;
// If the stream is not readable, return
2025-01-05 20:49:34 -05:00
if (!stream.CanRead)
2024-07-17 15:19:15 -04:00
return false;
// Set internal variables
2024-02-28 19:19:50 -05:00
FileStream? outputStream = null;
// Get the output folder name from the first rebuild rom
2020-08-28 20:46:12 -07:00
string fileName;
2024-10-19 23:17:37 -04:00
if (_writeToParent)
2024-02-28 19:19:50 -05:00
fileName = Path.Combine(outDir, TextHelper.RemovePathUnsafeCharacters(baseFile.Filename) ?? string.Empty);
2020-08-28 20:46:12 -07:00
else
2024-02-28 21:59:13 -05:00
#if NET20 || NET35
fileName = Path.Combine(Path.Combine(outDir, TextHelper.RemovePathUnsafeCharacters(baseFile.Parent) ?? string.Empty), TextHelper.RemovePathUnsafeCharacters(baseFile.Filename) ?? string.Empty);
#else
2024-02-28 19:19:50 -05:00
fileName = Path.Combine(outDir, TextHelper.RemovePathUnsafeCharacters(baseFile.Parent) ?? string.Empty, TextHelper.RemovePathUnsafeCharacters(baseFile.Filename) ?? string.Empty);
2024-02-28 21:59:13 -05:00
#endif
// Replace any incorrect directory characters
if (Path.DirectorySeparatorChar == '\\')
fileName = fileName.Replace('/', '\\');
else if (Path.DirectorySeparatorChar == '/')
fileName = fileName.Replace('\\', '/');
try
{
// If the full output path doesn't exist, create it
2024-02-28 19:19:50 -05:00
string? dir = Path.GetDirectoryName(fileName);
if (dir != null && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
// Overwrite output files by default
2020-12-08 00:13:22 -08:00
outputStream = File.Create(fileName);
2024-07-17 15:19:15 -04:00
if (outputStream == null)
return false;
2025-01-05 20:49:34 -05:00
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.Begin);
2024-07-17 15:19:15 -04:00
// Copy the input stream to the output
int bufferSize = 4096 * 128;
byte[] ibuffer = new byte[bufferSize];
int ilen;
2025-01-05 20:49:34 -05:00
while ((ilen = stream.Read(ibuffer, 0, bufferSize)) > 0)
2024-07-17 15:19:15 -04:00
{
outputStream.Write(ibuffer, 0, ilen);
outputStream.Flush();
}
2020-08-28 21:38:27 -07:00
2024-07-17 15:19:15 -04:00
outputStream.Dispose();
2024-07-18 00:00:23 -04:00
// Try to set the creation time
try
{
if (!string.IsNullOrEmpty(baseFile.Date))
File.SetCreationTime(fileName, DateTime.Parse(baseFile.Date));
}
catch { }
2024-07-17 15:19:15 -04:00
return true;
}
catch (Exception ex)
{
_logger.Error(ex);
2024-07-17 15:19:15 -04:00
return false;
}
finally
{
outputStream?.Dispose();
}
}
/// <inheritdoc/>
2025-01-05 20:49:34 -05:00
public bool Write(List<string> files, string outDir, List<BaseFile>? baseFiles)
{
throw new NotImplementedException();
}
#endregion
}
}