internal TorrentFileStream GetStream(TorrentFile file, FileAccess access)
        {
            TorrentFileStream s = FindStream(file.FullPath);

            if (s != null)
            {
                // If we are requesting write access and the current stream does not have it
                if (((access & FileAccess.Write) == FileAccess.Write) && !s.CanWrite)
                {
                    Logger.Log(null, "Didn't have write permission - reopening");
                    CloseAndRemove(s);
                    s = null;
                }
                else
                {
                    // Place the filestream at the end so we know it's been recently used
                    list.Remove(s);
                    list.Add(s);
                }
            }

            if (s == null)
            {
                if (!File.Exists(file.FullPath))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(file.FullPath));
                    SparseFile.CreateSparse(file.FullPath, file.Length);
                }
                s = new TorrentFileStream(file, FileMode.OpenOrCreate, access, FileShare.Read);

                // Ensure that we truncate existing files which are too large
                if (s.Length > file.Length)
                {
                    if (!s.CanWrite)
                    {
#if NETSTANDARD1_5
                        s.Dispose();
#else
                        s.Close();
#endif
                        s = new TorrentFileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
                    }
                    s.SetLength(file.Length);
                }

                Add(s);
            }

            return(s);
        }
 private void CloseAndRemove(TorrentFileStream s)
 {
     Logger.Log(null, "Closing and removing: {0}", s.Path);
     list.Remove(s);
     s.Dispose();
 }