static async Task <bool> P_TryRecognizeStreamContentAsXmlAsync(Stream stream, XmlReaderSettings xmlReaderSettings) { stream.EnsureNotNull(nameof(stream)); xmlReaderSettings.EnsureNotNull(nameof(xmlReaderSettings)); // if (stream.CanSeek) { var xmlReader = default(XmlReader); var textReader = default(TextReader); var initialInputStreamPosition = default(long?); var tryException = default(Exception); try { Func <Stream, bool, TextReader> createTextReader = (locInputStream, locLeaveInputStreamOpen) => new StreamReader( stream: locInputStream, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: TextReaderWriterUtilities.DefaultBufferSize, leaveOpen: locLeaveInputStreamOpen); // initialInputStreamPosition = stream.Position; textReader = createTextReader(stream, true); var xmlReaderSettingsClone = xmlReaderSettings.Clone(); xmlReaderSettingsClone.DtdProcessing = DtdProcessing.Prohibit; xmlReaderSettingsClone.CloseInput = false; xmlReaderSettingsClone.IgnoreComments = xmlReaderSettingsClone.IgnoreProcessingInstructions = xmlReaderSettingsClone.IgnoreWhitespace = true; xmlReader = XmlReader.Create(textReader, xmlReaderSettingsClone); // bool isXml; try { isXml = await xmlReader .ReadAsync() .ConfigureAwait(false); isXml = isXml && xmlReader.NodeType == XmlNodeType.XmlDeclaration; // stream.Position = initialInputStreamPosition.Value; initialInputStreamPosition = null; } catch (XmlException) { isXml = false; } // textReader.Dispose(); (xmlReader as IDisposable)?.Dispose(); // return(isXml); } catch (Exception firstException) { tryException = firstException; throw; } finally { try { if (initialInputStreamPosition.HasValue) { try { stream.Position = initialInputStreamPosition.Value; } catch (ObjectDisposedException) { } } if (tryException != null) { textReader?.Dispose(); (xmlReader as IDisposable)?.Dispose(); } } catch (Exception firstException) { if (tryException == null) { throw; } else { throw tryException.ToAggregateException(firstException); } } } } else { return(false); } }