internal TorrentFileStream GetStream(TorrentFile file, FileAccess access)
{
var fileStream = FindStream(file.FullPath);
if (fileStream != null)
{
// If we are requesting write access and the current stream does not have it
if (((access & FileAccess.Write) == FileAccess.Write) && !fileStream.CanWrite)
{
Logger.Log (null, "Didn't have write permission - reopening");
CloseAndRemove(fileStream);
fileStream = null;
}
else
{
// Place the filestream at the end so we know it's been recently used
_list.Remove(fileStream);
_list.Add(fileStream);
}
}
if (fileStream == null)
{
if (File.Exists(file.FullPath) == false)
{
Directory.CreateDirectory(Path.GetDirectoryName(file.FullPath));
SparseFile.CreateSparse(file.FullPath, file.Length);
}
fileStream = new TorrentFileStream (file, FileMode.OpenOrCreate, access, FileShare.Read);
// Ensure that we truncate existing files which are too large
if (fileStream.Length > file.Length) {
if (!fileStream.CanWrite) {
fileStream.Close();
fileStream = new TorrentFileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
}
fileStream.SetLength(file.Length);
}
Add(fileStream);
}
return fileStream;
}