public void Stop()
        {
            lock (syncLock)
            {
                isRunning = false;

                Connection.Message -= new MessageEvent(Connection_Message);

                foreach (CsvFileWriter file in csvFileWriters.Values)
                {
                    file.Dispose();
                }

                // stash the path before the move (if one is to take place).
                string writtenToBasePath = Directory;

                // Rename directory now that device information has been read from the file.
                if (Connection.ConnectionType == ConnectionType.File)
                {
                    string resolvedSessionDescriptor = Helper.CleanFileName(Connection.Settings.GetDeviceDescriptor());

                    string resolvedDirectory = Path.Combine(rootDirectory, resolvedSessionDescriptor);

                    if (Directory.Equals(resolvedDirectory) == false)
                    {
                        Helper.MoveDirectory(Directory, resolvedDirectory, true);

                        ConnectionDescriptor = resolvedSessionDescriptor;
                    }
                }

                Metadata.DirectoryName = ConnectionDescriptor;

                // Use the last available setting for the meta data.
                Metadata.DeviceInformation.SetValues(Connection.Settings.DeviceInformation);

                Metadata.TimeStamps.FirstTimeTag = firstTimestamp;
                Metadata.TimeStamps.LastTimeTag  = lastTimestamp;
                Metadata.ConnectionInformation.ConnectionInfo = Connection.ConnectionInfo;
                Metadata.ConnectionInformation.ConnectionType = Connection.ConnectionType;

                string basePath = Directory;

                foreach (CsvFileWriter file in csvFileWriters.Values)
                {
                    // use the stashed path for substring-ing as the directory might have changed since the CSV file was created.
                    Metadata.FilesCreated.Add(file.FilePath.Substring(writtenToBasePath.Length + 1), file.MessageCount);
                }

                Metadata.Statistics.SetValues(Connection.CommunicationStatistics);

                Metadata.Save(Path.Combine(Directory, "Device.xml"));

                Connection.Settings.Save(Path.Combine(Directory, "Settings.txt"), null);
            }
        }