I have an app that downloads files from our server using SFTP with SSH.NET, recursively through a few folders. The download works just fine, the first time you click the download button. When the download is complete, and you try to click the download button again, an exception is thrown at the File.Create(destFilePath)
saying that the process cannot access the file because it is being used by another process. I thought that by encapsulating this stream with using
that it would handle the disposing properly. I can't figure out why it won't let me download a second time without closing and re-opening the app, any help would be appreciated!
public void DownloadDirectory(SftpClient sftpClient, string sourceRemotePath, string destLocalPath)
{
Directory.CreateDirectory(destLocalPath);
IEnumerable<SftpFile> files = sftpClient.ListDirectory(sourceRemotePath);
foreach (SftpFile file in files)
{
if (source != null)
{
if (source.IsCancellationRequested)
{
sftpClient.Disconnect();
return;
}
}
if ((file.Name != ".") && (file.Name != ".."))
{
string sourceFilePath = sourceRemotePath + "/" + file.Name;
string destFilePath = Path.Combine(destLocalPath, file.Name);
if (file.IsDirectory)
{
DownloadDirectory(sftpClient, sourceFilePath, destFilePath);
}
else
{
using (Stream fileStream = File.Create(destFilePath))
{
SftpFileAttributes attrs = sftpClient.GetAttributes(file.FullName);
int max = (int)attrs.Size;
progressBar1.Invoke((MethodInvoker)delegate
{
progressBar1.Maximum = max;
label1.Text = "Downloading " + file.Name + "...";
});
sftpClient.DownloadFile(sourceFilePath, fileStream, DownloadProgressBar);
}
}
}
}
}