Skip to content

Commit

Permalink
Added method to check if file is supported instead of waiting for exc…
Browse files Browse the repository at this point in the history
…eption
  • Loading branch information
robertobasile84 authored and decriptor committed Aug 31, 2024
1 parent a8421d9 commit 32dff43
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions src/TaglibSharp/File.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1235,6 +1235,37 @@ public static File Create (string path, string mimetype, ReadStyle propertiesSty
return Create (new LocalFileAbstraction (path), mimetype, propertiesStyle);
}

/// <summary>
/// Returns true if the file is supported
/// </summary>
/// <param name="path">The file path</param>
/// <returns>True if supported, false otherwise</returns>
public static bool IsSupportedFile (string path)
{
var abstraction = new LocalFileAbstraction (path);

return IsSupportedFile (abstraction);
}

private static bool IsSupportedFile(IFileAbstraction abstraction)
{
string mimetype = GetMimeType (abstraction);

return FileTypes.AvailableTypes.ContainsKey (mimetype);
}

private static string GetMimeType (IFileAbstraction abstraction)
{
string ext = string.Empty;

int index = abstraction.Name.LastIndexOf (".") + 1;

if (index >= 1 && index < abstraction.Name.Length)
ext = abstraction.Name.Substring (index, abstraction.Name.Length - index);

return $"taglib/{ext.ToLower (CultureInfo.InvariantCulture)}";
}

/// <summary>
/// Creates a new instance of a <see cref="File" /> subclass
/// for a specified file abstraction, mime-type, and read
Expand Down Expand Up @@ -1269,16 +1300,7 @@ public static File Create (string path, string mimetype, ReadStyle propertiesSty
/// </exception>
public static File Create (IFileAbstraction abstraction, string mimetype, ReadStyle propertiesStyle)
{
if (mimetype == null) {
string ext = string.Empty;

int index = abstraction.Name.LastIndexOf (".") + 1;

if (index >= 1 && index < abstraction.Name.Length)
ext = abstraction.Name.Substring (index, abstraction.Name.Length - index);

mimetype = "taglib/" + ext.ToLower (CultureInfo.InvariantCulture);
}
mimetype ??= GetMimeType (abstraction);

foreach (var resolver in file_type_resolvers) {
var file = resolver (abstraction, mimetype, propertiesStyle);
Expand All @@ -1287,7 +1309,7 @@ public static File Create (IFileAbstraction abstraction, string mimetype, ReadSt
return file;
}

if (!FileTypes.AvailableTypes.ContainsKey (mimetype))
if (!IsSupportedFile(abstraction))
throw new UnsupportedFormatException (
string.Format (CultureInfo.InvariantCulture, "{0} ({1})", abstraction.Name, mimetype));

Expand Down

0 comments on commit 32dff43

Please sign in to comment.