diff --git a/examples/BatchSet/BatchSet.cs b/examples/BatchSet/Program.cs similarity index 71% rename from examples/BatchSet/BatchSet.cs rename to examples/BatchSet/Program.cs index bdc5279f2..8edbbd287 100644 --- a/examples/BatchSet/BatchSet.cs +++ b/examples/BatchSet/Program.cs @@ -2,25 +2,29 @@ using System.Collections.Generic; using TagLib; -public class BatchSet +namespace BatchSet; + +public class Program { - private enum Mode { - Tag, Value, File + enum Mode { + Tag, + Value, + File } - + public static void Main(string [] args) { if(args.Length < 3) { Console.Error.WriteLine ("USAGE: BatchSet.exe -tag value [-tag2 value ...] File1 [File2 ...]"); return; } - + Mode mode = Mode.Tag; - List files = new List (); - Dictionary tags = new Dictionary (); - + var files = new List (); + var tags = new Dictionary (); + string tag = null; - + foreach (string str in args) { if (mode == Mode.Tag) { if (str [0] == '-') { @@ -30,30 +34,30 @@ public static void Main(string [] args) tag = str.Substring (1); mode = Mode.Value; } - + continue; } mode = Mode.File; } - + if (mode == Mode.Value) { if (!tags.ContainsKey (tag)) tags.Add (tag, str); mode = Mode.Tag; continue; } - + if (mode == Mode.File) files.Add (str); } - + foreach (string filename in files) { - TagLib.File file = TagLib.File.Create (filename); + using var file = TagLib.File.Create (filename); if (file == null) continue; - - Console.WriteLine ("Updating Tags For: " + filename); - + + Console.WriteLine ($"Updating Tags For: {filename}"); + foreach (string key in tags.Keys) { string value = tags [key]; try { @@ -63,11 +67,7 @@ public static void Main(string [] args) if (number == 1) { file.RemoveTags (TagTypes.Id3v2); } else { - TagLib.Id3v2.Tag v2 = - file.GetTag (TagTypes.Id3v2, true) - as TagLib.Id3v2.Tag; - - if (v2 != null) + if (file.GetTag (TagTypes.Id3v2, true) is TagLib.Id3v2.Tag v2) v2.Version = number; } break; @@ -75,7 +75,7 @@ public static void Main(string [] args) file.Tag.Album = value; break; case "artists": - file.Tag.AlbumArtists = value.Split (new char [] {';'}); + file.Tag.AlbumArtists = value.Split ([';']); break; case "comment": file.Tag.Comment = value; @@ -84,7 +84,7 @@ public static void Main(string [] args) file.Tag.Lyrics = value; break; case "composers": - file.Tag.Composers = value.Split (new char [] {';'}); + file.Tag.Composers = value.Split ([';']); break; case "disc": file.Tag.Disc = uint.Parse (value); @@ -93,10 +93,10 @@ public static void Main(string [] args) file.Tag.DiscCount = uint.Parse (value); break; case "genres": - file.Tag.Genres = value.Split (new char [] {';'}); + file.Tag.Genres = value.Split ([';']); break; case "performers": - file.Tag.Performers = value.Split (new char [] {';'}); + file.Tag.Performers = value.Split ([';']); break; case "title": file.Tag.Title = value; @@ -111,20 +111,20 @@ public static void Main(string [] args) file.Tag.Year = uint.Parse (value); break; case "pictures": - List pics = new List (); + var pics = new List (); if (!string.IsNullOrEmpty (value)) - foreach (string path in value.Split (new char [] {';'})) { + foreach (string path in value.Split ([';'])) { pics.Add (new Picture (path)); } file.Tag.Pictures = pics.ToArray (); break; } } catch (Exception e) { - Console.WriteLine ("Error setting tag " + key + ":"); + Console.WriteLine ($"Error setting tag {key}:"); Console.WriteLine (e); } } - + file.Save(); } } diff --git a/examples/GenerateTestFixture/GenerateTestFixture.cs b/examples/GenerateTestFixture/Program.cs similarity index 91% rename from examples/GenerateTestFixture/GenerateTestFixture.cs rename to examples/GenerateTestFixture/Program.cs index 0d4135b85..eae96188b 100644 --- a/examples/GenerateTestFixture/GenerateTestFixture.cs +++ b/examples/GenerateTestFixture/Program.cs @@ -16,15 +16,16 @@ using TagLib.IFD.Tags; using TagLib.Xmp; -public class GenerateTestFixtureApp +namespace GenerateTestFixture; + +public class Program { - private static MD5 md5 = MD5.Create (); + static MD5 md5 = MD5.Create (); // Helper to run a process and capture output, error, and exit code - private static bool RunProcess(string exe, string args, out string output, out string error, out int exitCode) + static bool RunProcess (string exe, string args, out string output, out string error, out int exitCode) { - var startInfo = new ProcessStartInfo - { + var startInfo = new ProcessStartInfo { FileName = exe, Arguments = args, RedirectStandardOutput = true, @@ -34,17 +35,17 @@ private static bool RunProcess(string exe, string args, out string output, out s }; using var process = new Process { StartInfo = startInfo }; - process.Start(); - output = process.StandardOutput.ReadToEnd(); - error = process.StandardError.ReadToEnd(); - process.WaitForExit(); + process.Start (); + output = process.StandardOutput.ReadToEnd (); + error = process.StandardError.ReadToEnd (); + process.WaitForExit (); exitCode = process.ExitCode; return exitCode == 0; } - public static void Main (string [] args) + public static void Main (string[] args) { - if(args.Length != 2) { + if (args.Length != 2) { Console.Error.WriteLine ("USAGE: mono GenerateTestFixture.exe NAME PATH"); return; } @@ -64,8 +65,7 @@ public static void Main (string [] args) static void GenerateIFDFixture (string name, string path) { // First run exiv2 on it. - string output, err; int code; - var result = RunProcess("listData", $"e {path}", out output, out err, out code); + var result = RunProcess ("listData", $"e {path}", out var output, out var err, out var code); if (!result) { Console.Error.WriteLine ("Invoking listData failed, are you running from the examples folder?\n" + err); return; @@ -78,7 +78,7 @@ static void GenerateIFDFixture (string name, string path) if (parts.Length == 0 || line.Trim ().Equals (string.Empty) || parts.Length != 5) continue; string tag_label = parts[0]; - ushort tag = ushort.Parse (parts[1].Substring(2), System.Globalization.NumberStyles.HexNumber); + ushort tag = ushort.Parse (parts[1].Substring (2), System.Globalization.NumberStyles.HexNumber); string ifd = parts[2]; string type = parts[3]; uint length = uint.Parse (parts[4]); @@ -146,15 +146,15 @@ static void GenerateIFDFixture (string name, string path) } else if (ifd.Equals ("GPSInfo")) { EmitTestIFDEntryOpen ("gps_structure", 0, tag, ifd); } else if (ifd.Equals ("CanonCs")) { - EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort) CanonMakerNoteEntryTag.CameraSettings, ifd); + EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort)CanonMakerNoteEntryTag.CameraSettings, ifd); } else if (ifd.Equals ("CanonSi")) { - EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort) CanonMakerNoteEntryTag.ShotInfo, ifd); + EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort)CanonMakerNoteEntryTag.ShotInfo, ifd); } else if (ifd.Equals ("CanonCf")) { - EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort) CanonMakerNoteEntryTag.CustomFunctions, ifd); + EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort)CanonMakerNoteEntryTag.CustomFunctions, ifd); } else if (ifd.Equals ("CanonPi")) { - EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort) CanonMakerNoteEntryTag.PictureInfo, ifd); + EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort)CanonMakerNoteEntryTag.PictureInfo, ifd); } else if (ifd.Equals ("CanonFi")) { - EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort) 0x93, ifd); + EmitTestIFDEntryOpen ("makernote_structure", 0, (ushort)0x93, ifd); } else if (ifd.Equals ("PanasonicRaw")) { EmitTestIFDEntryOpen ("pana_structure", 0, tag, ifd); } else if (sub_ifds.ContainsKey (ifd)) { @@ -171,7 +171,7 @@ static void GenerateIFDFixture (string name, string path) // And the fist both entries are combined to a long by exiv2. if (tag == 0x0001) { string val1 = ((ushort)uint.Parse (val)).ToString (); - string val2 = ((ushort) (uint.Parse (val) >> 16)).ToString (); + string val2 = ((ushort)(uint.Parse (val) >> 16)).ToString (); EmitTestIFDIndexedShortEntry (tag, val1); EmitTestIFDIndexedShortEntry (tag + 1, val2); } else { @@ -240,8 +240,7 @@ static void GenerateIFDFixture (string name, string path) static void GenerateXMPFixture (string name, string path) { // First run exiv2 on it. - string output, err; int code; - var result = RunProcess("listData", $"x {path}", out output, out err, out code); + var result = RunProcess ("listData", $"x {path}", out var output, out var err, out var code); if (!result) { Console.Error.WriteLine ("Invoking exiv2 failed, do you have it installed?\n" + err); return; @@ -257,13 +256,13 @@ static void GenerateXMPFixture (string name, string path) Write ("XmpTag xmp = file.GetTag (TagTypes.XMP) as XmpTag;"); // Build prefix lookup dictionary. - Type t = typeof(XmpTag); - foreach (var member in t.GetMembers()) { + Type t = typeof (XmpTag); + foreach (var member in t.GetMembers ()) { if (!member.Name.EndsWith ("_NS")) continue; string val = (member as System.Reflection.FieldInfo).GetValue (null) as string; - string prefix = XmpTag.NamespacePrefixes [val]; - xmp_prefixes [prefix] = member.Name; + string prefix = XmpTag.NamespacePrefixes[val]; + xmp_prefixes[prefix] = member.Name; } foreach (string line in output.Split ('\n')) { @@ -303,9 +302,9 @@ static void EmitXmpTest (string label, string type, uint length, string val) // Plain node int index = 0; string name = parts[2]; - if (parts[2].EndsWith("]")) { + if (parts[2].EndsWith ("]")) { int index_start = parts[2].LastIndexOf ("["); - string index_str = parts[2].Substring (index_start+1, parts[2].Length-index_start-2); + string index_str = parts[2].Substring (index_start + 1, parts[2].Length - index_start - 2); index = int.Parse (index_str); name = parts[2].Substring (0, index_start); } @@ -323,7 +322,7 @@ static void EmitXmpTest (string label, string type, uint length, string val) Write ($"node = node.GetChild ({ns}, \"{name}\");"); Write ("Assert.IsNotNull (node);"); } else { - throw new Exception ("Can't navigate to "+node); + throw new Exception ("Can't navigate to " + node); } } @@ -338,7 +337,7 @@ static void EmitXmpTest (string label, string type, uint length, string val) Write ($"Assert.AreEqual (\"{val}\", node.Children [0].Value);"); } else if (type.Equals ("LangAlt") && length == 1) { var langparts = val.Split ([' '], 2); - string lang = langparts[0].Substring (langparts[0].IndexOf ('"')+1, langparts [0].Length - langparts[0].IndexOf ('"')-2); + string lang = langparts[0].Substring (langparts[0].IndexOf ('"') + 1, langparts[0].Length - langparts[0].IndexOf ('"') - 2); Write ($"Assert.AreEqual (\"{lang}\", node.Children [0].GetQualifier (XmpTag.XML_NS, \"lang\").Value);"); Write ($"Assert.AreEqual (\"{langparts[1]}\", node.Children [0].Value);"); } else if (type.Equals ("XmpSeq") && length == 1) { @@ -347,7 +346,7 @@ static void EmitXmpTest (string label, string type, uint length, string val) Write ($"Assert.AreEqual ({length}, node.Children.Count);"); Write ($"Assert.AreEqual (\"{val}\", node.Children [0].Value);"); } else if (type.Equals ("XmpSeq") && length > 1) { - string [] vals = val.Split (','); + string[] vals = val.Split (','); Write ("Assert.AreEqual (XmpNodeType.Seq, node.Type);"); Write ("Assert.AreEqual (\"\", node.Value);"); Write ($"Assert.AreEqual ({length}, node.Children.Count);"); @@ -355,12 +354,12 @@ static void EmitXmpTest (string label, string type, uint length, string val) for (int i = 0; i < length; i++) { var builder = new List (); for (int j = 0; j < per_iter; j++) { - builder.Add (vals[per_iter*i + j].Trim ()); + builder.Add (vals[per_iter * i + j].Trim ()); } Write ($"Assert.AreEqual (\"{string.Join (", ", builder.ToArray ())}\", node.Children [{i}].Value);"); } } else if (type.Equals ("XmpBag") && length > 1) { - string [] vals = val.Split (','); + string[] vals = val.Split (','); Write ("Assert.AreEqual (XmpNodeType.Bag, node.Type);"); Write ("Assert.AreEqual (\"\", node.Value);"); Write ($"Assert.AreEqual ({length}, node.Children.Count);"); @@ -373,7 +372,7 @@ static void EmitXmpTest (string label, string type, uint length, string val) for (int i = 0; i < length; i++) { var builder = new List (); for (int j = 0; j < per_iter; j++) { - builder.Add (vals[per_iter*i + j].Trim ()); + builder.Add (vals[per_iter * i + j].Trim ()); } Write ($"Assert.IsTrue (children_array.Contains (\"{string.Join (", ", builder.ToArray ())}\"));"); } @@ -396,8 +395,7 @@ static void EmitXmpTest (string label, string type, uint length, string val) static string ExtractKey (string file, string key) { - string output, err; int code; - var result = RunProcess("extractKey", $"{file} {key}", out output, out err, out code); + var result = RunProcess ("extractKey", $"{file} {key}", out var output, out var err, out var code); if (!result) { Console.Error.WriteLine ("Invoking extractKey failed, are you running from the examples folder?\n" + err); return string.Empty; @@ -418,10 +416,11 @@ static string GetXmpNs (string prefix) prefix = "MicrosoftPhoto"; if (xmp_prefixes.TryGetValue (prefix, out var result)) return $"XmpTag.{result}"; - throw new Exception ("Unknown namespace prefix: "+prefix); + throw new Exception ("Unknown namespace prefix: " + prefix); } - static bool IsPartOfMakernote (string ifd) { + static bool IsPartOfMakernote (string ifd) + { return ifd.Equals ("MakerNote") || ifd.Equals ("Canon") || ifd.Equals ("Sony") || @@ -436,7 +435,7 @@ static bool IsPartOfMakernote (string ifd) { static void EmitHeader (string name, string path) { int start = path.LastIndexOf ('/'); - string filename = path.Substring (start+1); + string filename = path.Substring (start + 1); Write ("// TODO: This file is automatically generated"); Write ("// TODO: Further manual verification is needed"); Write (); @@ -493,7 +492,8 @@ static void EmitFooter () static bool iop_emitted = false; static bool gps_emitted = false; - static void EnsureIFD (string ifd) { + static void EnsureIFD (string ifd) + { if (ifd.Equals ("PanasonicRaw")) { if (is_panasonic_raw) return; @@ -691,19 +691,19 @@ static void EmitTestIFDSShortArrayEntry (string val) static void EmitTestIFDRationalEntry (string val) { Write ("Assert.IsNotNull (entry as RationalIFDEntry, \"Entry is not a rational!\");"); - string[] parts = val.Split('/'); + string[] parts = val.Split ('/'); Write ($"Assert.AreEqual ({parts[0]}, (entry as RationalIFDEntry).Value.Numerator);"); Write ($"Assert.AreEqual ({parts[1]}, (entry as RationalIFDEntry).Value.Denominator);"); } static void EmitTestIFDRationalArrayEntry (string val) { - var parts = val.Split(' '); + var parts = val.Split (' '); Write ("Assert.IsNotNull (entry as RationalArrayIFDEntry, \"Entry is not a rational array!\");"); Write ("var parts = (entry as RationalArrayIFDEntry).Values;"); Write ($"Assert.AreEqual ({parts.Length}, parts.Length);"); for (int i = 0; i < parts.Length; i++) { - var pieces = parts[i].Split('/'); + var pieces = parts[i].Split ('/'); Write ($"Assert.AreEqual ({pieces[0]}, parts[{i}].Numerator);"); Write ($"Assert.AreEqual ({pieces[1]}, parts[{i}].Denominator);"); } @@ -712,19 +712,19 @@ static void EmitTestIFDRationalArrayEntry (string val) static void EmitTestIFDSRationalEntry (string val) { Write ("Assert.IsNotNull (entry as SRationalIFDEntry, \"Entry is not a srational!\");"); - string[] parts = val.Split('/'); + string[] parts = val.Split ('/'); Write ($"Assert.AreEqual ({parts[0]}, (entry as SRationalIFDEntry).Value.Numerator);"); Write ($"Assert.AreEqual ({parts[1]}, (entry as SRationalIFDEntry).Value.Denominator);"); } static void EmitTestIFDSRationalArrayEntry (string val) { - var parts = val.Split(' '); + var parts = val.Split (' '); Write ("Assert.IsNotNull (entry as SRationalArrayIFDEntry, \"Entry is not a srational array!\");"); Write ("var parts = (entry as SRationalArrayIFDEntry).Values;"); Write ($"Assert.AreEqual ({parts.Length}, parts.Length);"); for (int i = 0; i < parts.Length; i++) { - var pieces = parts[i].Split('/'); + var pieces = parts[i].Split ('/'); Write ($"Assert.AreEqual ({pieces[0]}, parts[{i}].Numerator);"); Write ($"Assert.AreEqual ({pieces[1]}, parts[{i}].Denominator);"); } @@ -785,26 +785,26 @@ static void EmitByteArrayComparison (string val, string type, string type_desc) { Write ($"Assert.IsNotNull (entry as {type}, \"Entry is not {type_desc}!\");"); Write ($"var parsed_bytes = (entry as {type}).Data.Data;"); - var parts = val.Trim ().Split(' '); + var parts = val.Trim ().Split (' '); if (parts.Length < 512) { Write ($"var bytes = new byte [] {{ {string.Join (", ", parts)} }};"); Write ("Assert.AreEqual (bytes, parsed_bytes);"); } else { // Starting with 512 byte items, we compare based on an MD5 hash, should be faster and reduces // the size of the test fixtures. - byte [] data = new byte [parts.Length]; + byte[] data = new byte[parts.Length]; for (int i = 0; i < parts.Length; i++) { - data [i] = byte.Parse (parts [i]); + data[i] = byte.Parse (parts[i]); } var hash = md5.ComputeHash (data); - StringBuilder shash = new StringBuilder (); + var shash = new StringBuilder (); for (int i = 0; i < hash.Length; i++) { shash.Append (hash[i].ToString ("x2")); } Write ("var parsed_hash = Utils.Md5Encode (parsed_bytes);"); - Write ($"Assert.AreEqual (\"{shash.ToString ()}\", parsed_hash);"); + Write ($"Assert.AreEqual (\"{shash}\", parsed_hash);"); Write ($"Assert.AreEqual ({parts.Length}, parsed_bytes.Length);"); } } @@ -851,7 +851,7 @@ static void EmitTestIFDIndexedShortEntry (int index, string val) Write ($"Assert.AreEqual ({parts[i]}, (entry as ShortArrayIFDEntry).Values [{index + i}]);"); } -#region IFD tag names lookup + #region IFD tag names lookup static Dictionary> tag_names = null; @@ -904,14 +904,14 @@ static void IndexTagType (string ifd, Type t, string typename) if (!tag_names.ContainsKey (ifd)) tag_names[ifd] = new Dictionary (); foreach (string name in Enum.GetNames (t)) { - ushort tag = (ushort) Enum.Parse (t, name); + ushort tag = (ushort)Enum.Parse (t, name); tag_names[ifd][tag] = $"{typename}.{name}"; } } -#endregion + #endregion -#region Code emission + #region Code emission static int level = 0; @@ -936,5 +936,5 @@ static void Write (string str) level++; } -#endregion + #endregion } diff --git a/examples/ListSupportedMimeTypes/ListSupportedMimeTypes.cs b/examples/ListSupportedMimeTypes/Program.cs similarity index 73% rename from examples/ListSupportedMimeTypes/ListSupportedMimeTypes.cs rename to examples/ListSupportedMimeTypes/Program.cs index 2149b1a31..cf204b609 100644 --- a/examples/ListSupportedMimeTypes/ListSupportedMimeTypes.cs +++ b/examples/ListSupportedMimeTypes/Program.cs @@ -1,7 +1,9 @@ using System; using TagLib; -public class ListSupportedMimeTypes +namespace ListSupportedMimeTypes; + +public class Program { public static void Main() { diff --git a/examples/ParsePhoto/ParsePhoto.cs b/examples/ParsePhoto/ParsePhoto.cs deleted file mode 100644 index cf0a48080..000000000 --- a/examples/ParsePhoto/ParsePhoto.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; - -public class ParsePhotoApp -{ - public static void Main (string [] args) - { - if(args.Length == 0) { - Console.Error.WriteLine("USAGE: mono ParsePhoto.exe PATH [...]"); - return; - } - - foreach (string path in args) - ParsePhoto (path); - } - - static void ParsePhoto (string path) - { - TagLib.File file = null; - - try { - file = TagLib.File.Create(path); - } catch (TagLib.UnsupportedFormatException) { - Console.WriteLine ("UNSUPPORTED FILE: " + path); - Console.WriteLine (String.Empty); - Console.WriteLine ("---------------------------------------"); - Console.WriteLine (String.Empty); - return; - } - - var image = file as TagLib.Image.File; - if (file == null) { - Console.WriteLine ("NOT AN IMAGE FILE: " + path); - Console.WriteLine (String.Empty); - Console.WriteLine ("---------------------------------------"); - Console.WriteLine (String.Empty); - return; - } - - Console.WriteLine (String.Empty); - Console.WriteLine (path); - Console.WriteLine (String.Empty); - - Console.WriteLine("Tags in object : " + image.TagTypes); - Console.WriteLine (String.Empty); - - Console.WriteLine("Comment : " + image.ImageTag.Comment); - Console.Write("Keywords : "); - foreach (var keyword in image.ImageTag.Keywords) { - Console.Write (keyword + " "); - } - Console.WriteLine (); - Console.WriteLine("Rating : " + image.ImageTag.Rating); - Console.WriteLine("DateTime : " + image.ImageTag.DateTime); - Console.WriteLine("Orientation : " + image.ImageTag.Orientation); - Console.WriteLine("Software : " + image.ImageTag.Software); - Console.WriteLine("ExposureTime : " + image.ImageTag.ExposureTime); - Console.WriteLine("FNumber : " + image.ImageTag.FNumber); - Console.WriteLine("ISOSpeedRatings : " + image.ImageTag.ISOSpeedRatings); - Console.WriteLine("FocalLength : " + image.ImageTag.FocalLength); - Console.WriteLine("FocalLength35mm : " + image.ImageTag.FocalLengthIn35mmFilm); - Console.WriteLine("Make : " + image.ImageTag.Make); - Console.WriteLine("Model : " + image.ImageTag.Model); - - if (image.Properties != null) { - Console.WriteLine("Width : " + image.Properties.PhotoWidth); - Console.WriteLine("Height : " + image.Properties.PhotoHeight); - Console.WriteLine("Type : " + image.Properties.Description); - } - - Console.WriteLine (); - Console.WriteLine("Writable? : " + image.Writeable.ToString ()); - Console.WriteLine("Corrupt? : " + image.PossiblyCorrupt.ToString ()); - - if (image.PossiblyCorrupt) { - foreach (string reason in image.CorruptionReasons) { - Console.WriteLine (" * " + reason); - } - } - - Console.WriteLine ("---------------------------------------"); - } -} diff --git a/examples/ParsePhoto/Program.cs b/examples/ParsePhoto/Program.cs new file mode 100644 index 000000000..f1173c415 --- /dev/null +++ b/examples/ParsePhoto/Program.cs @@ -0,0 +1,84 @@ +using System; + +namespace ParsePhoto; + +public class Program +{ + public static void Main (string [] args) + { + if(args.Length == 0) { + Console.Error.WriteLine("USAGE: mono ParsePhoto.exe PATH [...]"); + return; + } + + foreach (string path in args) + ParsePhoto (path); + } + + static void ParsePhoto (string path) + { + TagLib.File file; + try { + file = TagLib.File.Create(path); + } catch (TagLib.UnsupportedFormatException) { + Console.WriteLine ("UNSUPPORTED FILE: " + path); + Console.WriteLine (); + Console.WriteLine ("---------------------------------------"); + Console.WriteLine (); + return; + } + + var image = file as TagLib.Image.File; + if (file == null) { + Console.WriteLine ($"NOT AN IMAGE FILE: {path}"); + Console.WriteLine (); + Console.WriteLine ("---------------------------------------"); + Console.WriteLine (); + return; + } + + Console.WriteLine (); + Console.WriteLine (path); + Console.WriteLine (); + + Console.WriteLine($"Tags in object : {image.TagTypes}"); + Console.WriteLine (); + + Console.WriteLine($"Comment : {image.ImageTag.Comment}"); + Console.Write("Keywords : "); + foreach (var keyword in image.ImageTag.Keywords) { + Console.Write ($"{keyword} "); + } + + Console.WriteLine (); + Console.WriteLine($"Rating : {image.ImageTag.Rating}"); + Console.WriteLine($"DateTime : {image.ImageTag.DateTime}"); + Console.WriteLine($"Orientation : {image.ImageTag.Orientation}"); + Console.WriteLine($"Software : {image.ImageTag.Software}"); + Console.WriteLine($"ExposureTime : {image.ImageTag.ExposureTime}"); + Console.WriteLine($"FNumber : {image.ImageTag.FNumber}"); + Console.WriteLine($"ISOSpeedRatings : {image.ImageTag.ISOSpeedRatings}"); + Console.WriteLine($"FocalLength : {image.ImageTag.FocalLength}"); + Console.WriteLine($"FocalLength35mm : {image.ImageTag.FocalLengthIn35mmFilm}"); + Console.WriteLine($"Make : {image.ImageTag.Make}"); + Console.WriteLine($"Model : {image.ImageTag.Model}"); + + if (image.Properties != null) { + Console.WriteLine($"Width : {image.Properties.PhotoWidth}"); + Console.WriteLine($"Height : {image.Properties.PhotoHeight}"); + Console.WriteLine($"Type : {image.Properties.Description}"); + } + + Console.WriteLine (); + Console.WriteLine($"Writable? : {image.Writeable}"); + Console.WriteLine($"Corrupt? : {image.PossiblyCorrupt}"); + + if (image.PossiblyCorrupt) { + foreach (string reason in image.CorruptionReasons) { + Console.WriteLine ($" * {reason}"); + } + } + + Console.WriteLine ("---------------------------------------"); + } +} diff --git a/examples/ReadFromUri/ReadFromUri.cs b/examples/ReadFromUri/Program.cs similarity index 95% rename from examples/ReadFromUri/ReadFromUri.cs rename to examples/ReadFromUri/Program.cs index a817af4e3..d3f7b98d2 100644 --- a/examples/ReadFromUri/ReadFromUri.cs +++ b/examples/ReadFromUri/Program.cs @@ -3,7 +3,8 @@ using TagLib; -public class ReadFromUri +namespace ReadFromUri; +public class Program { public static void Write (string name, object value) { @@ -30,8 +31,8 @@ public static void Main (string[] args) TagLib.File file; try { - var file_info = new FileInfo (uri); - uri = new Uri (file_info.FullName).ToString (); + var fileInfo = new FileInfo (uri); + uri = new Uri (fileInfo.FullName).ToString (); } catch { } @@ -136,8 +137,5 @@ public FileAbstraction (string file) public Stream WriteStream => new FileStream (Name, FileMode.Open); - public void CloseStream (Stream stream) - { - stream.Close (); - } + public void CloseStream (Stream stream) => stream.Close (); } diff --git a/examples/SetPictures/Program.cs b/examples/SetPictures/Program.cs new file mode 100644 index 000000000..bd9b449bf --- /dev/null +++ b/examples/SetPictures/Program.cs @@ -0,0 +1,31 @@ +using TagLib; + +using File = TagLib.File; + +namespace SetPictures; + +public class Program +{ + public static void Main (string[] args) + { + if (args.Length < 2) { + Console.Error.WriteLine ("USAGE: mono SetPictures.exe AUDIO_PATH IMAGE_PATH_1[...IMAGE_PATH_N]"); + return; + } + + var file = File.Create (args[0]); + Console.WriteLine ($"Current picture count: {file.Tag.Pictures.Length}"); + + var pictures = new Picture[args.Length - 1]; + + for (int i = 1; i < args.Length; i++) { + var picture = new Picture (args[i]); + pictures[i - 1] = picture; + } + + file.Tag.Pictures = pictures; + file.Save (); + + Console.WriteLine ($"New picture count: {file.Tag.Pictures.Length}"); + } +} diff --git a/examples/SetPictures/SetPictures.cs b/examples/SetPictures/SetPictures.cs deleted file mode 100644 index 2869b42dc..000000000 --- a/examples/SetPictures/SetPictures.cs +++ /dev/null @@ -1,32 +0,0 @@ -using TagLib; - -using File = TagLib.File; - -namespace Examples -{ - public class SetPictures - { - public static void Main (string[] args) - { - if (args.Length < 2) { - Console.Error.WriteLine ("USAGE: mono SetPictures.exe AUDIO_PATH IMAGE_PATH_1[...IMAGE_PATH_N]"); - return; - } - - var file = File.Create (args[0]); - Console.WriteLine ("Current picture count: " + file.Tag.Pictures.Length); - - var pictures = new Picture[args.Length - 1]; - - for (int i = 1; i < args.Length; i++) { - var picture = new Picture (args[i]); - pictures[i - 1] = picture; - } - - file.Tag.Pictures = pictures; - file.Save (); - - Console.WriteLine ("New picture count: " + file.Tag.Pictures.Length); - } - } -} diff --git a/examples/StripImageData/StripImageData.cs b/examples/StripImageData/Program.cs similarity index 59% rename from examples/StripImageData/StripImageData.cs rename to examples/StripImageData/Program.cs index 98c9b8b8a..e38d1540a 100644 --- a/examples/StripImageData/StripImageData.cs +++ b/examples/StripImageData/Program.cs @@ -2,13 +2,15 @@ using File = TagLib.File; -public class StripImageData +namespace StripImageData; + +public class Program { - private static byte[] image_data = new byte[] { + static readonly byte[] image_data = [ 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3F, 0x00, 0x8C, 0x80, 0x07, 0xFF, 0xD9 - }; + ]; public static void Main (string [] args) { @@ -17,9 +19,9 @@ public static void Main (string [] args) return; } - ImageFile file = new ImageFile (args [0]); - - file.Mode = File.AccessMode.Write; + var file = new ImageFile (args[0]) { + Mode = File.AccessMode.Write + }; long greatest_segment_position = 0; long greatest_segment_length = 0; @@ -48,7 +50,7 @@ public static void Main (string [] args) return; } - System.Console.WriteLine ("Stripping data segment at {0}", greatest_segment_position); + Console.WriteLine ($"Stripping data segment at {greatest_segment_position}"); file.RemoveBlock (greatest_segment_position, greatest_segment_length); file.Seek (greatest_segment_position); @@ -56,17 +58,17 @@ public static void Main (string [] args) file.Mode = File.AccessMode.Closed; } - private static long SkipDataSegment (ImageFile file) + static long SkipDataSegment (ImageFile file) { long position = file.Tell; // skip sos maker if (file.ReadBlock (2).ToUInt () != 0xFFDA) - throw new Exception (String.Format ("Not a data segment at position: {0}", position)); + throw new Exception ($"Not a data segment at position: {position}"); while (true) { - if (0xFF == (byte) file.ReadBlock (1)[0]) { - byte maker = (byte) file.ReadBlock (1)[0]; + if (0xFF == file.ReadBlock (1)[0]) { + byte maker = file.ReadBlock (1)[0]; if (maker != 0x00 && (maker <= 0xD0 || maker >= 0xD7)) break; @@ -75,42 +77,41 @@ private static long SkipDataSegment (ImageFile file) long length = file.Tell - position - 2; - System.Console.WriteLine ("Data segment of length {0} found at {1}", length, position); + Console.WriteLine ($"Data segment of length {length} found at {position}"); return length; } - private class ImageFile : File { + class ImageFile : File { // Hacky implementation to make use of some methods defined in TagLib.File - public ImageFile (string path) - : base (new File.LocalFileAbstraction (path)) {} + public ImageFile (string path) : base (new LocalFileAbstraction (path)) {} - public override Tag GetTag (TagLib.TagTypes type, bool create) + public override Tag GetTag (TagTypes type, bool create) { - throw new System.NotImplementedException (); + throw new NotImplementedException (); } public override Properties Properties { get { - throw new System.NotImplementedException (); + throw new NotImplementedException (); } } - public override void RemoveTags (TagLib.TagTypes types) + public override void RemoveTags (TagTypes types) { - throw new System.NotImplementedException (); + throw new NotImplementedException (); } public override void Save () { - throw new System.NotImplementedException (); + throw new NotImplementedException (); } public override Tag Tag { get { - throw new System.NotImplementedException (); + throw new NotImplementedException (); } } } diff --git a/src/Debug/Program.cs b/src/Debug/Program.cs index d10d3be38..03119062e 100644 --- a/src/Debug/Program.cs +++ b/src/Debug/Program.cs @@ -4,174 +4,172 @@ using TagLib; using File = System.IO.File; -namespace Debug +namespace Debug; + +/// +/// Stub program to debug some scenarios. Modify it as you need, this is not meant to be reuseable program. +/// +class Program { + static readonly string AssemblyLocation = Path.GetDirectoryName (Assembly.GetAssembly (typeof (Program)).Location); + public static readonly string Samples = Path.Combine (AssemblyLocation, "..", "..", "..", "..", "TaglibSharp.Tests", "samples"); + /// - /// Stub program to debug some scenarios. Modify it as you need, this is not meant to be reuseable program. + /// Output message on the console and on the Visual Studio Output /// - class Program + /// + static void Log (string str) { - static readonly string AssemblyLocation = Path.GetDirectoryName (Assembly.GetAssembly (typeof (Program)).Location); - public static readonly string Samples = Path.Combine (AssemblyLocation, "..", "..", "..", "..", "TaglibSharp.Tests", "samples"); - - /// - /// Ouput message on the console and on the Visual Studio Output - /// - /// - static void Log (string str) - { - Console.WriteLine (str); - System.Diagnostics.Debug.WriteLine (str); - } + Console.WriteLine (str); + System.Diagnostics.Debug.WriteLine (str); + } + + static void Main (string[] args) + { + Log ("--------------------"); + Log ($"* Start : Samples directory: {Samples}"); + Log (""); - static void Main (string[] args) - { - Log ("--------------------"); - Log ("* Start : Samples directory: " + Samples); - Log (""); - - // Override command arguments - args = new[] { "sample.wav" }; - - foreach (var fname in args) { - var fpath = Samples + fname; - var tpath = Samples + "tmpwrite" + Path.GetExtension (fname); - - Log ("+ File : " + fpath); - if (!File.Exists (fpath)) { - Log (" # File not found: " + fpath); - continue; - } - - Log (" read : " + fpath); - var rfile = TagLib.File.Create (fpath); - Log (" Type : " + rfile.MimeType); - - File.Copy (fpath, tpath, true); - - var file = TagLib.File.Create (tpath); - Log (" Type : " + file.MimeType); - - Log (" rboy1 test start : " + file.MimeType); - - var MKVTag = (TagLib.Matroska.Tag)file.GetTag (TagTypes.Matroska); - MKVTag.Title = "my Title"; - MKVTag.Set ("SUBTITLE", null, "my SubTitle"); - MKVTag.Set ("DESCRIPTION", null, "my Description"); - MKVTag.Set ("TVCHANNEL", null, "my Network"); - MKVTag.Set ("LAW_RATING", null, "my Rating"); - MKVTag.Set ("ACTOR", null, "my MediaCredits"); - MKVTag.Set ("GENRE", null, "my Genres"); - MKVTag.Set ("SEASON", null, "my Season"); - MKVTag.Set ("EPISODE", null, "my Episode"); - - var bannerFile = Samples + "sample_invalidifdoffset.jpg"; - var videoPicture = new Picture (bannerFile); - MKVTag.Pictures = new IPicture[] { videoPicture }; - - Log (" rboy1 test save : " + file.MimeType); - file.Save (); - - Log (" rboy1 test read : " + file.MimeType); - var tagFile = TagLib.File.Create (tpath); - - Log (" rboy1 test end : " + file.MimeType); - - var tag = file.Tag; - var pics = file.Tag.Pictures; - - var mtag = (TagLib.Matroska.Tag)file.GetTag (TagTypes.Matroska); - mtag.PerformersRole = new[] { "TEST role 1", "TEST role 2" }; - - Log (" Picture : " + pics[0].Description); - - var tracks = mtag.Tags.Tracks; - var audiotag = mtag.Tags.Get (tracks[1]); - if (audiotag != null) { - audiotag.Clear (); - audiotag.Title = "The Noise"; - audiotag.Set ("DESCRIPTION", null, "Useless background noise"); - } - - Log (" Erase : " + tag.Title); - file.RemoveTags (TagTypes.Matroska); - file.Save (); - - Log (" Write : " + tag.Title); - - tag.TitleSort = "title, TEST"; - tag.AlbumSort = "album, TEST"; - tag.PerformersSort = new[] { "performer 1, TEST", "performer 2, TEST" }; - tag.ComposersSort = new[] { "composer 1, TEST", "composer 2, TEST" }; - tag.AlbumArtistsSort = new[] { "album artist 1, TEST", "album artist 2, TEST" }; - - - tag.Album = "TEST album"; - tag.AlbumArtists = new[] { "TEST album artist 1", "TEST album artist 2" }; - tag.BeatsPerMinute = 120; - tag.Comment = "TEST comment"; - tag.Composers = new[] { "TEST composer 1", "TEST composer 2" }; - tag.Conductor = "TEST conductor"; - tag.Copyright = "TEST copyright"; - tag.Disc = 1; - tag.DiscCount = 2; - tag.Genres = new[] { "TEST genre 1", "TEST genre 2" }; - tag.Grouping = "TEST grouping"; - tag.Lyrics = "TEST lyrics 1\r\nTEST lyrics 2"; - tag.Performers = new[] { "TEST performer 1", "TEST performer 2" }; - tag.Title = "TEST title"; - tag.Track = 5; - tag.TrackCount = 10; - tag.Year = 1999; - - // Insert new picture - Array.Resize (ref pics, 2); - pics[1] = new Picture (Samples + "sample_sony2.jpg"); - file.Tag.Pictures = pics; - - file.Save (); - - - Log (" Done : " + tag.Title); - - // Now read it again - file = TagLib.File.Create (tpath); - tag = file.Tag; - mtag = (TagLib.Matroska.Tag)file.GetTag (TagTypes.Matroska); - - Log (" Read : " + tag.Title); - - Log (" Album : " + tag.Album); - Log (" JoinedAlbumArtists : " + tag.JoinedAlbumArtists); - Log (" BeatsPerMinute : " + tag.BeatsPerMinute); - Log (" Comment : " + tag.Comment); - Log (" JoinedComposers : " + tag.JoinedComposers); - Log (" Conductor : " + tag.Conductor); - Log (" Copyright : " + tag.Copyright); - Log (" Disc : " + tag.Disc); - Log (" DiscCount : " + tag.DiscCount); - Log (" JoinedGenres : " + tag.JoinedGenres); - Log (" Grouping : " + tag.Grouping); - Log (" Lyrics : " + tag.Lyrics); - Log (" JoinedPerformers : " + tag.JoinedPerformers); - Log (" Title : " + tag.Title); - Log (" Track : " + tag.Track); - Log (" TrackCount : " + tag.TrackCount); - Log (" Year : " + tag.Year); - - Log (" TitleSort : " + tag.TitleSort); - Log (" AlbumSort : " + tag.AlbumSort); - Log (" PerformersSort : " + tag.JoinedPerformersSort); - Log (" ComposersSort : " + string.Join ("; ", tag.ComposersSort)); - Log (" AlbumArtistsSort : " + string.Join ("; ", tag.AlbumArtistsSort)); - - - Log (" PerformersRole : " + string.Join ("; ", mtag.PerformersRole)); - - Log (" Done : " + tag.Title); + // Override command arguments + args = ["sample.wav"]; + + foreach (var fname in args) { + var fpath = Samples + fname; + var tpath = $"{Samples}tmpwrite{Path.GetExtension (fname)}"; + + Log ($"+ File : {fpath}"); + if (!File.Exists (fpath)) { + Log ($" # File not found: {fpath}"); + continue; } - Log ("* End"); + Log ($" read : {fpath}"); + var rfile = TagLib.File.Create (fpath); + Log ($" Type : {rfile.MimeType}"); + + File.Copy (fpath, tpath, true); + + var file = TagLib.File.Create (tpath); + Log ($" Type : {file.MimeType}"); + + Log ($" rboy1 test start : {file.MimeType}"); + + var MKVTag = (TagLib.Matroska.Tag)file.GetTag (TagTypes.Matroska); + MKVTag.Title = "my Title"; + MKVTag.Set ("SUBTITLE", null, "my SubTitle"); + MKVTag.Set ("DESCRIPTION", null, "my Description"); + MKVTag.Set ("TVCHANNEL", null, "my Network"); + MKVTag.Set ("LAW_RATING", null, "my Rating"); + MKVTag.Set ("ACTOR", null, "my MediaCredits"); + MKVTag.Set ("GENRE", null, "my Genres"); + MKVTag.Set ("SEASON", null, "my Season"); + MKVTag.Set ("EPISODE", null, "my Episode"); + + var bannerFile = $"{Samples}sample_invalidifdoffset.jpg"; + var videoPicture = new Picture (bannerFile); + MKVTag.Pictures = [videoPicture]; + + Log ($" rboy1 test save : {file.MimeType}"); + file.Save (); + + Log ($" rboy1 test read : {file.MimeType}"); + var tagFile = TagLib.File.Create (tpath); + + Log ($" rboy1 test end : {file.MimeType}"); + + var tag = file.Tag; + var pics = file.Tag.Pictures; + + var mtag = (TagLib.Matroska.Tag)file.GetTag (TagTypes.Matroska); + mtag.PerformersRole = ["TEST role 1", "TEST role 2"]; + + Log ($" Picture : {pics[0].Description}"); + + var tracks = mtag.Tags.Tracks; + var audiotag = mtag.Tags.Get (tracks[1]); + if (audiotag != null) { + audiotag.Clear (); + audiotag.Title = "The Noise"; + audiotag.Set ("DESCRIPTION", null, "Useless background noise"); + } + + Log ($" Erase : {tag.Title}"); + file.RemoveTags (TagTypes.Matroska); + file.Save (); + + Log ($" Write : {tag.Title}"); + + tag.TitleSort = "title, TEST"; + tag.AlbumSort = "album, TEST"; + tag.PerformersSort = ["performer 1, TEST", "performer 2, TEST"]; + tag.ComposersSort = ["composer 1, TEST", "composer 2, TEST"]; + tag.AlbumArtistsSort = ["album artist 1, TEST", "album artist 2, TEST"]; + + + tag.Album = "TEST album"; + tag.AlbumArtists = ["TEST album artist 1", "TEST album artist 2"]; + tag.BeatsPerMinute = 120; + tag.Comment = "TEST comment"; + tag.Composers = ["TEST composer 1", "TEST composer 2"]; + tag.Conductor = "TEST conductor"; + tag.Copyright = "TEST copyright"; + tag.Disc = 1; + tag.DiscCount = 2; + tag.Genres = ["TEST genre 1", "TEST genre 2"]; + tag.Grouping = "TEST grouping"; + tag.Lyrics = "TEST lyrics 1\r\nTEST lyrics 2"; + tag.Performers = ["TEST performer 1", "TEST performer 2"]; + tag.Title = "TEST title"; + tag.Track = 5; + tag.TrackCount = 10; + tag.Year = 1999; + + // Insert new picture + Array.Resize (ref pics, 2); + pics[1] = new Picture ($"{Samples}sample_sony2.jpg"); + file.Tag.Pictures = pics; + + file.Save (); + + + Log ($" Done : {tag.Title}"); + + // Now read it again + file = TagLib.File.Create (tpath); + tag = file.Tag; + mtag = (TagLib.Matroska.Tag)file.GetTag (TagTypes.Matroska); + + Log ($" Read : {tag.Title}"); + + Log ($" Album : {tag.Album}"); + Log ($" JoinedAlbumArtists : {tag.JoinedAlbumArtists}"); + Log ($" BeatsPerMinute : {tag.BeatsPerMinute}"); + Log ($" Comment : {tag.Comment}"); + Log ($" JoinedComposers : {tag.JoinedComposers}"); + Log ($" Conductor : {tag.Conductor}"); + Log ($" Copyright : {tag.Copyright}"); + Log ($" Disc : {tag.Disc}"); + Log ($" DiscCount : {tag.DiscCount}"); + Log ($" JoinedGenres : {tag.JoinedGenres}"); + Log ($" Grouping : {tag.Grouping}"); + Log ($" Lyrics : {tag.Lyrics}"); + Log ($" JoinedPerformers : {tag.JoinedPerformers}"); + Log ($" Title : {tag.Title}"); + Log ($" Track : {tag.Track}"); + Log ($" TrackCount : {tag.TrackCount}"); + Log ($" Year : {tag.Year}"); + + Log ($" TitleSort : {tag.TitleSort}"); + Log ($" AlbumSort : {tag.AlbumSort}"); + Log ($" PerformersSort : {tag.JoinedPerformersSort}"); + Log ($" ComposersSort : {string.Join ("; ", tag.ComposersSort)}"); + Log ($" AlbumArtistsSort : {string.Join ("; ", tag.AlbumArtistsSort)}"); + + Log ($" PerformersRole : {string.Join ("; ", mtag.PerformersRole)}"); + + Log ($" Done : {tag.Title}"); } + + Log ("* End"); } }