Exemplo n.º 1
0
        private async Task <DownLoadedFileModel> DownLoadAFileProcessAsync(SftpFile file, SftpClient sftp, string SavedPath, SemaphoreSlim SemaphoreForRecord)
        {
            /// if an exception occurred, the LocalPath is null and ExceptionMessage has value in DownLoadFileModel.
            return(await Task.Run(() =>
            {
                DownLoadedFileModel rslt = new DownLoadedFileModel
                {
                    FtpPath = file.FullName,
                    LocalPath = $"{SavedPath}\\{Path.GetFileName(file.FullName)}",
                };

                SemaphoreForRecord.Wait();
                try
                {
                    using (FileStream wrt = new FileStream(rslt.LocalPath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        sftp.DownloadFile(file.FullName, wrt);
                        wrt.Flush();
                    }
                }
                catch (Exception ex)
                {
                    rslt.LocalPath = null;
                    rslt.ExceptionMessage = ex.Message;
                }
                finally
                {
                    SemaphoreForRecord.Release();
                }
                return rslt;
            }));
        }
Exemplo n.º 2
0
        private async Task <DownLoadedFileModel> DownLoadAFileProcessAsync(string file, FTPSettings ftpSetting, SemaphoreSlim SemaphoreForRecord)
        {
            /// if an exception occurred, the LocalPath is null and ExceptionMessage has value in DownLoadFileModel.
            return(await Task.Run(() =>
            {
                DownLoadedFileModel result = new DownLoadedFileModel();
                result.FtpPath = file;
                result.LocalPath = $"{ftpSetting.OutPutPath}\\{Path.GetFileName(file)}";

                SemaphoreForRecord.Wait();
                try
                {
                    var fileRequest = GetFtpWebRequest(file, ftpSetting);
                    fileRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                    using var response = fileRequest.GetResponse();
                    using var responseStream = response.GetResponseStream();
                    using var localFile = new FileStream(result.LocalPath, FileMode.Create, FileAccess.Write);
                    responseStream.CopyTo(localFile);
                    localFile.Flush();
                }
                catch (Exception ex)
                {
                    result.LocalPath = null;
                    result.ExceptionMessage = ex.Message;
                }
                finally
                {
                    SemaphoreForRecord.Release();
                }
                return result;
            }));
        }