-1

Please tell me what is wrong in this code. The FileService also throws downloaded file content is null or empty or format of the URI cant be determined. The Fileservice class seems to be working for upload image which has another method. The FTP credentials dont seem wrong either. Still the error persists. I have already uploaded the performance.pdf in the FTP server provided below and the path also seems to be working.

FileService.cs :

public async Task<byte[]> GetFile(string fileName, CancellationToken cancellationToken) 
{ 
if (String.IsNullOrEmpty(_ftpConfig.Hostname))
 { 
var filePath = $"{_ftpConfig.Hostname}/{fileName}"; byte[] byteData = File.ReadAllBytes(filePath); return byteData; } 

var request = WebRequest.Create($"{_ftpConfig.Hostname}/{fileName}") as FtpWebRequest;
 request.Credentials = new NetworkCredential(_ftpConfig.Username, _ftpConfig.Password);
 request.Method = WebRequestMethods.Ftp.DownloadFile;

 try
 {
     using var response = (FtpWebResponse)await request.GetResponseAsync();
     using var responseStream = response.GetResponseStream();

     using var memoryStream = new MemoryStream();
     responseStream.CopyTo(memoryStream);
     var bytes = memoryStream.ToArray();
     return bytes;
 }
 catch (Exception ex)
 {
     throw new Exception(ex.Message);
 }
}

Method to download the file:

public async Task<OperationResult<byte[]>> DownloadPerformanceAppraisal(CancellationToken cancellationToken)
 { 
var operation = new OperationResult<byte[]>(); string fileName = "Performance_Appraisal/Download/performance.pdf"; 
try
 {
     // Download file from FTP server using fileService
     byte[] fileContent;
     try
     {
         fileContent = await _fileService.GetFile(fileName, cancellationToken);
     }
     catch (Exception ex)
     {
         operation.Exception = new Exception("Error downloading file: " + ex.Message);
         operation.Status = HttpStatusCode.InternalServerError;
         return operation;
     }

     if (fileContent == null || fileContent.Length == 0)
     {
         operation.Exception = new Exception("Downloaded file content is null or empty.");
         operation.Status = HttpStatusCode.InternalServerError;
         return operation;
     }

     operation.Result = fileContent;
     operation.Status = HttpStatusCode.OK;
 }
 catch (Exception ex)
 {
     await _errorLogService.LogException(operation, ex);
 }

 return operation;
}
2
  • 1
    What is the full constructed URI? Commented Jul 1 at 12:50
  • it's something like FTP://xxxxxxxxxxxxx/filePath. But thanks for the response, i found out the problem. Apperntly, I was missing a '/' in the path
    – Achyut
    Commented Jul 2 at 5:35

0

Browse other questions tagged or ask your own question.