/// <summary> /// Reads the FIT binary file header and crc to check compatibility and integrity. /// Also checks data reords size. /// Returns true if file is ok (not corrupt). ///</summary> /// <param name="fitStream">Seekable (file)stream to parse.</param> public bool CheckIntegrity(Stream fitStream) { bool isValid; try { // Is there a valid header? Header header = new Header(fitStream); isValid = header.IsValid(); // Are there as many data bytes as the header claims? isValid &= ((header.Size + header.DataSize + 2) == fitStream.Length); // Is the file CRC ok? byte[] data = new byte[fitStream.Length]; fitStream.Position = 0; fitStream.Read(data, 0, data.Length); isValid &= (CRC.Calc16(data, data.Length) == 0x0000); return isValid; } catch(FitException) { return false; } }
/// <summary> /// Reads a FIT binary file. /// </summary> /// <param name="fitStream">Seekable (file)stream to parse.</param> /// <returns> /// Returns true if reading finishes successfully. /// </returns> public bool Read(Stream fitStream) { bool readOK = true; try { // Attempt to read header fileHeader = new Header(fitStream); readOK &= fileHeader.IsValid(); if (!readOK) { throw new FitException("FIT decode error: File is not FIT format. Check file header data type."); } if ((fileHeader.ProtocolVersion & Fit.ProtocolVersionMajorMask) > (Fit.ProtocolMajorVersion << Fit.ProtocolVersionMajorShift)) { // The decoder does not support decode accross protocol major revisions throw new FitException(String.Format("FIT decode error: Protocol Version {0}.X not supported by SDK Protocol Ver{1}.{2} ", (fileHeader.ProtocolVersion & Fit.ProtocolVersionMajorMask) >> Fit.ProtocolVersionMajorShift, Fit.ProtocolMajorVersion, Fit.ProtocolMinorVersion)); } // Read data messages and definitions while (fitStream.Position < fitStream.Length - 2) { DecodeNextMessage(fitStream); } // Is the file CRC ok? byte[] data = new byte[fitStream.Length]; fitStream.Position = 0; fitStream.Read(data, 0, data.Length); readOK &= (CRC.Calc16(data, data.Length) == 0x0000); } catch (EndOfStreamException e) { readOK = false; Debug.WriteLine("{0} caught and ignored. ", e.GetType().Name); throw new FitException("Decode:Read - Unexpected End of File", e); } return readOK; }
/// <summary> /// Reads the file header to check if the file is FIT. /// Does not check CRC. /// Returns true if file is FIT. /// </summary> /// <param name="fitStream"> Seekable (file)stream to parse</param> public bool IsFIT(Stream fitStream) { try { // Does the header contain the flag string ".FIT"? Header header = new Header(fitStream); return header.IsValid(); } // If the header is malformed the ctor could throw an exception catch (FitException) { return false; } }