public static VERSION RecognizeISBN(string isbn) { isbn = SanitizeISBN(isbn); if (isbn.Length == 13 && isbn.StartsWith(Spec.PREFIX) && Spec.IsISBN13SpecCompliant(isbn)) { return(VERSION.ISBN13); } if (isbn.Length == 10 && Spec.IsISBN10SpecCompliant(isbn)) { return(VERSION.ISBN10); } return(VERSION.INVALID); }
/// <summary> /// Converts the isbn. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> /// <exception cref="System.FormatException"> /// </exception> public string ConvertISBN(string input) { // Sanitize input var sanitized = Recognizer.SanitizeISBN(input); // Try to determine the ISBN Version used VERSION version = Recognizer.RecognizeISBN(sanitized); // Throw if unable to determine (likely malformed string) if (version == VERSION.INVALID) { throw new FormatException($"Invalid ISBN Format for {input} detected!"); } // Throw if the ISBN contains invalid characters if (!(version == VERSION.ISBN10 ? Spec.IsISBN10SpecCompliant(sanitized) : Spec.IsISBN13SpecCompliant(sanitized))) { throw new FormatException($"{input} is not spec compliant!"); } // Warn if checksum calculated is not the one in the ISBN (malformed/incorrect ISBN) var checksum = (version == VERSION.ISBN10 ? Spec.CalculateChecksum10(sanitized) : Spec.CalculateChecksum13(sanitized)); if (checksum != sanitized[sanitized.Length - 1]) { OnMalformedISBN?.Invoke(input, $"Checksum mismatch for {input}! It should be {checksum.ToString().ToUpper()}!"); } var isbn = (version == VERSION.ISBN10 ? Converter.ConvertISBN10ToISBN13(sanitized) : Converter.ConvertISBN13ToISBN10(sanitized)); // Check if input already contains separation (and thus can simply copied) if (input.Contains("-") || input.Contains(" ")) { // Remove the prefix and the first separator if it exists if (version == VERSION.ISBN13) { input = input.Substring(Spec.PREFIX.Length + 1); } var separator = "-"; // Check if '-' or ' ' are used for separation if (input.Contains(" ")) { separator = " "; } // Place the separators into the new string while (input.Contains(separator)) { var index = input.IndexOf(separator); isbn = isbn.Insert((version == VERSION.ISBN10 ? Spec.PREFIX.Length : 0) + index, "-"); input = input.Substring(0, index) + "+" + input.Substring(index + 1); } // We also need to hyphenate the prefix if it exists // This and the check above are inverted since we need to modify the target ISBN version if (version == VERSION.ISBN10) { isbn = isbn.Insert(Spec.PREFIX.Length, "-"); } } else { isbn = HyphenateISBN(isbn); } return(isbn); }