예제 #1
0
        public string GetFTPFile(string fileName, FtpCredentials ftpCredentials)
        {
            string base64String = string.Empty;

            try
            {
                using (WebClient request = new WebClient())
                {
                    NetworkCredential networkcredentials = new NetworkCredential(ftpCredentials.FTPUserName, ftpCredentials.FTPPassword);
                    request.Credentials = networkcredentials;

                    try
                    {
                        byte[] fileData = request.DownloadData(string.Format("{0}{1}", ftpCredentials.FTPAddress, fileName));

                        base64String = Convert.ToBase64String(fileData, 0, fileData.Length);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(base64String);
        }
예제 #2
0
        public List <Files> DownloadMultipleFiles(UploadImageStatus image, FtpCredentials ftpCredentials)
        {
            List <Files> fileList = new List <Files>();

            try
            {
                WebClient request  = new WebClient();
                string    fileName = string.Format("{0}/{1}", image.Url, image.Name);
                string    url      = string.Format("{0}{1}", ftpCredentials.FTPAddress, fileName);
                request.Credentials = new NetworkCredential(ftpCredentials.FTPUserName, ftpCredentials.FTPPassword);
                byte[] bytes = request.DownloadData(url);

                fileList.Add(new Files
                {
                    FileName = fileName,
                    Bytes    = bytes
                });
            }
            catch (WebException ex)
            {
                throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
            }

            return(fileList);
        }
예제 #3
0
        public string[] ViewFile(string folder, FtpCredentials credentaials)
        {
            string ftp = credentaials.Url + folder;

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp);

            request.Method = WebRequestMethods.Ftp.ListDirectory;

            //Enter FTP Server credentials.
            request.Credentials = new NetworkCredential(credentaials.username, credentaials.password);
            request.UsePassive  = true;
            request.UseBinary   = true;
            request.EnableSsl   = false;
            List <string> list = new List <string>();

            //Fetch the Response and read it into a MemoryStream object.

            using (var response = (FtpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream, true))
                    {
                        while (!reader.EndOfStream)
                        {
                            list.Add(reader.ReadLine());
                        }
                    }
                }
            }

            return(list.ToArray());
        }
예제 #4
0
        public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executing at: {DateTime.Now}");

            FtpCredentials ftpCredentials = new FtpCredentials()
            {
                Hostname    = ConfigurationManager.AppSettings["FtpHostname"],
                InboundDir  = ConfigurationManager.AppSettings["FtpInboundDir"],
                OutboundDir = ConfigurationManager.AppSettings["FtpOutboundDir"],
                Password    = ConfigurationManager.AppSettings["FtpPassword"],
                Username    = ConfigurationManager.AppSettings["FtpUsername"],
                Key         = ConfigurationManager.AppSettings["FtpKey"]
            };
            string             accountName        = ConfigurationManager.AppSettings["StorageAccountName"];
            string             accountKey         = ConfigurationManager.AppSettings["StorageAccountKey"];
            string             blobContainerName  = ConfigurationManager.AppSettings["BlobContainerName"];
            StorageCredentials storageCredentials = new StorageCredentials(accountName, accountKey);

            OmsCredentials omsCredentials = new OmsCredentials()
            {
                WorkspaceId = ConfigurationManager.AppSettings["OmsWorkspaceId"],
                SharedKey   = ConfigurationManager.AppSettings["OmsLogAnalyticsSharedKey"]
            };

            ILog omsLogger = new OmsLogger(omsCredentials);

            ;
            BlobFtpAgent  theAgent = new RebexFtpAgent(ftpCredentials, storageCredentials, omsLogger);
            List <String> fnames   = theAgent.GetFileNames();

            if (fnames.Count == 0)
            {
                log.Info("No files found");
            }
            else
            {
                foreach (string fname in fnames)
                {
                    log.Info("Transfering Inbound File: " + fname);
                    var logEntry = theAgent.Get(fname, blobContainerName);
                    if (logEntry != null)
                    {
                        if (logEntry.Result.Equals("Success"))
                        {
                            log.Info(fname + " Transferred");
                        }
                        else
                        {
                            log.Info("Failed to Transfer File " + fname);
                        }
                    }
                }
            }
        }
예제 #5
0
        public static void Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            FtpCredentials ftpCredentials = new FtpCredentials()
            {
                Hostname    = ConfigurationManager.AppSettings["FtpHostname"],
                InboundDir  = ConfigurationManager.AppSettings["FtpInboundDir"],
                OutboundDir = ConfigurationManager.AppSettings["FtpOutboundDir"],
                Password    = ConfigurationManager.AppSettings["FtpPassword"],
                Username    = ConfigurationManager.AppSettings["FtpUsername"],
                Key         = ConfigurationManager.AppSettings["FtpKey"]
            };
            BlobFtpAgent theAgent = new RebexFtpAgent(ftpCredentials, null, null);

            req.CreateResponse(HttpStatusCode.OK, "Hello ");
        }
예제 #6
0
        public FtpWebResponse DowloadFile(string folder, string filename, FtpCredentials credentaials)
        {
            if (!string.IsNullOrEmpty(folder) && !string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(credentaials.password) && !string.IsNullOrEmpty(credentaials.Url) && !string.IsNullOrEmpty(credentaials.username))
            {
                try
                {
                    //FTP Server URL.
                    string ftp = credentaials.Url + folder + "/" + filename;
                    //Create FTP Request.
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp);
                    request.Method = WebRequestMethods.Ftp.DownloadFile;

                    //Enter FTP Server credentials.
                    request.Credentials = new NetworkCredential(credentaials.username, credentaials.password);
                    request.UsePassive  = true;
                    request.UseBinary   = true;
                    request.EnableSsl   = false;

                    //Fetch the Response and read it into a MemoryStream object.
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    return(response);
                    //using (MemoryStream stream = new MemoryStream())
                    //{
                    //    //Download the File.
                    //    response.GetResponseStream().CopyTo(stream);
                    //    Response.AddHeader("content-disposition", "attachment;filename=" + filename);
                    //    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //    Response.BinaryWrite(stream.ToArray());
                    //    Response.End();
                    //}
                }
                catch (WebException ex)
                {
                    throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
                }
            }
            else
            {
                return(null);
            }
        }
        public IEnumerable <FtpItem> GetRemoteItems(FtpCredentials credentials, Uri myUri)
        {
            var request = (FtpWebRequest)WebRequest.Create(myUri);

            request.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
            request.Credentials = new NetworkCredential(credentials.User, credentials.Password);
            request.UsePassive  = true;
            request.UseBinary   = true;
            request.KeepAlive   = false;

            var returnList = new List <FtpItem>();

            using var response = (FtpWebResponse)request.GetResponse();
            using var reader   = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException());
            var list = reader.ReadToEnd().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in list)
            {
                var parts = line.Split(" ").ToList();
                //parts = parts.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
                parts = parts.Where(x => !string.IsNullOrEmpty(x)).ToList();
예제 #8
0
        public string DeleteFile(string folder, string filename, FtpCredentials credentaials)
        {
            if (!string.IsNullOrEmpty(folder) && !string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(credentaials.password) && !string.IsNullOrEmpty(credentaials.Url) && !string.IsNullOrEmpty(credentaials.username))
            {
                try
                {
                    string ftp = credentaials.Url + folder + "/" + filename;

                    List <string> existingfiles = ViewFile(folder, credentaials).ToList();
                    List <string> listsamefile  = existingfiles.Where(a => a.Contains(filename)).ToList();
                    string        responssse;
                    if (listsamefile.Count > 0)
                    {
                        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp);
                        request.Method      = WebRequestMethods.Ftp.DeleteFile;
                        request.Credentials = new NetworkCredential(credentaials.username, credentaials.password);
                        request.UsePassive  = true;
                        request.UseBinary   = true;
                        request.EnableSsl   = false;
                        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                        {
                            responssse = response.StatusDescription;
                        }
                    }
                    else
                    {
                        responssse = "No file found with this name";
                    }
                    return(responssse);
                }
                catch (Exception eexcx)
                {
                    return(eexcx.ToString());
                }
            }
            else
            {
                return("Please enter all the  credentials");
            }
        }
        private void ConnectForUpload()
        {
            if (_fileDestination == null)
            {
                try
                {
                    bool loggedIn = false;

                    FtpCredentials credentials = (FtpCredentials)_credentials[DestinationContext];
                    string username = credentials != null ? credentials.Username : _settings.Username;
                    string password = credentials != null ? credentials.Password : _settings.Password;

                    while (!loggedIn)
                    {
                        if (password == String.Empty)
                        {
                            CredentialsDomain cd = new CredentialsDomain(Res.Get(StringId.FtpLoginDomain), _settings.FtpServer, null, FtpIconBytes);
                            CredentialsPromptResult result = CredentialsHelper.PromptForCredentials(ref username, ref password, cd);
                            if (result == CredentialsPromptResult.Cancel || result == CredentialsPromptResult.Abort)
                            {
                                throw new OperationCancelledException();
                            }
                            else
                            {
                                //save the user/pass as appropriate
                                if (result == CredentialsPromptResult.SaveUsername)
                                {
                                    _settings.Username = username;
                                    _settings.Password = String.Empty;
                                }
                                else if (result == CredentialsPromptResult.SaveUsernameAndPassword)
                                {
                                    _settings.Username = username;
                                    _settings.Password = password;
                                }
                            }
                        }
                        try
                        {
                            // create and connect to the destination
                            _fileDestination = new WinInetFTPFileDestination(
                                _settings.FtpServer,
                                _settings.PublishPath,
                                username,
                                password);

                            _fileDestination.Connect();

                            //save the validated credentials so we don't need to prompt again later
                            _credentials[DestinationContext] = new FtpCredentials(DestinationContext, username, password);

                            loggedIn = true;
                        }
                        catch (LoginException)
                        {
                            loggedIn = false;
                            password = String.Empty;
                            _credentials.Remove(DestinationContext);
                        }
                    }

                    // calculate the target path and ensure that it exists
                    _fileDestination.InsureDirectoryExists(PostContext);
                }
                catch (Exception ex)
                {
                    WebPublishMessage message = WebPublishUtils.ExceptionToErrorMessage(ex);
                    throw new BlogClientFileTransferException(Res.Get(StringId.BCEFileTransferConnectingToDestination), message.Title, message.Text);
                }
            }
        }
예제 #10
0
        private void ConnectForUpload()
        {
            if (_fileDestination == null)
            {
                try
                {
                    bool loggedIn = false;

                    FtpCredentials credentials = (FtpCredentials)_credentials[DestinationContext];
                    string         username    = credentials != null ? credentials.Username : _settings.Username;
                    string         password    = credentials != null ? credentials.Password : _settings.Password;

                    while (!loggedIn)
                    {
                        if (password == String.Empty)
                        {
                            CredentialsDomain       cd     = new CredentialsDomain(Res.Get(StringId.FtpLoginDomain), _settings.FtpServer, null, FtpIconBytes);
                            CredentialsPromptResult result = CredentialsHelper.PromptForCredentials(ref username, ref password, cd);
                            if (result == CredentialsPromptResult.Cancel || result == CredentialsPromptResult.Abort)
                            {
                                throw new OperationCancelledException();
                            }
                            else
                            {
                                //save the user/pass as appropriate
                                if (result == CredentialsPromptResult.SaveUsername)
                                {
                                    _settings.Username = username;
                                    _settings.Password = String.Empty;
                                }
                                else if (result == CredentialsPromptResult.SaveUsernameAndPassword)
                                {
                                    _settings.Username = username;
                                    _settings.Password = password;
                                }
                            }
                        }
                        try
                        {
                            // create and connect to the destination
                            _fileDestination = new WinInetFTPFileDestination(
                                _settings.FtpServer,
                                _settings.PublishPath,
                                username,
                                password);

                            _fileDestination.Connect();

                            //save the validated credentials so we don't need to prompt again later
                            _credentials[DestinationContext] = new FtpCredentials(DestinationContext, username, password);

                            loggedIn = true;
                        }
                        catch (LoginException)
                        {
                            loggedIn = false;
                            password = String.Empty;
                            _credentials.Remove(DestinationContext);
                        }
                    }

                    // calculate the target path and ensure that it exists
                    _fileDestination.InsureDirectoryExists(PostContext);
                }
                catch (Exception ex)
                {
                    WebPublishMessage message = WebPublishUtils.ExceptionToErrorMessage(ex);
                    throw new BlogClientFileTransferException(Res.Get(StringId.BCEFileTransferConnectingToDestination), message.Title, message.Text);
                }
            }
        }
예제 #11
0
        public Response <List <UploadImageStatus> > SaveAttachment(string folderName, string claimId, int?userId, HttpRequestBase Request, FtpCredentials ftpCredentials)
        {
            string ftpResult    = string.Empty;
            string pathToCreate = $"{claimId}/{folderName}";
            List <UploadImageStatus>             lstimgstatus = new List <UploadImageStatus>();
            Response <List <UploadImageStatus> > response     = new Response <List <UploadImageStatus> >();

            PLRAttachmentVM PLRAttachmentVM = new PLRAttachmentVM
            {
                FtpUrl       = ftpCredentials.FTPAddress,
                PathToCreate = pathToCreate,
                FtpUsername  = ftpCredentials.FTPUserName,
                FtpPassword  = ftpCredentials.FTPPassword,
                ClaimId      = claimId,
                FolderName   = folderName,
                Status       = folderName.Substring(0, 1).ToUpper(),
                UserId       = userId.ToString(),
                Request      = Request
            };

            try
            {
                ftpResult = FtpIOExtensions.CreateFtpDirectory(PLRAttachmentVM);

                if (string.IsNullOrEmpty(ftpResult))
                {
                    ftpResult    = FtpIOExtensions.UploadFileToFtp(PLRAttachmentVM);
                    lstimgstatus = PLRDAO.UploadedImagesDetail(PLRAttachmentVM.ClaimId);

                    response.Status  = ResultStatus.Success;
                    response.Message = "Success";
                    response.Data    = lstimgstatus;
                }
            }
            catch (Exception ex)
            {
                LoggerService.LogException(ex);

                response.Status  = ResultStatus.Error;
                response.Message = "Error";
                response.Data    = lstimgstatus;
            }

            return(response);
        }
예제 #12
0
 protected BaseSupplier(FtpCredentials credentials)
 {
     _Credentials = credentials;
 }
예제 #13
0
        public List <KeyValuePair <string, string> > GetALLFilesFromFTP(string ClaimId, FtpCredentials ftpCredentials)
        {
            List <string> Entries = new List <string>();
            List <KeyValuePair <string, string> > FileName = new List <KeyValuePair <string, string> >();

            try
            {
                List <ClaimUploadStatus> FolderNames = Enum.GetValues(typeof(ClaimUploadStatus)).Cast <ClaimUploadStatus>().ToList();

                NetworkCredential networkcredentials = new NetworkCredential(ftpCredentials.FTPUserName, ftpCredentials.FTPPassword);

                foreach (ClaimUploadStatus foldername in FolderNames)
                {
                    //Create FTP Request.
                    string folderpath = string.Format("{0}/{1}", ftpCredentials.FTPAddress, ClaimId);

                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderpath);
                    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                    //Enter FTP Server credentials.
                    request.Credentials = networkcredentials;
                    request.UsePassive  = true;
                    request.UseBinary   = true;
                    request.EnableSsl   = false;
                    request.KeepAlive   = true;

                    //Fetch the Response and read it using StreamReader.
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        //Read the Response as String and split using New Line character.
                        Entries = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    }

                    response.Close();

                    //Loop and add details of each File to the DataTable.
                    foreach (string entry in Entries)
                    {
                        string[] splits = entry.Split(new string[] { " ", }, StringSplitOptions.RemoveEmptyEntries);

                        //Determine whether entry is for File or Directory
                        bool isFile = splits[0].Substring(0, 1) != "d";

                        if (isFile)
                        {
                            if (splits.Count() >= 8)
                            {
                                FileName.Add(new KeyValuePair <string, string>(foldername.ToString(), splits[8]));
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                LoggerService.LogExceptionsToDebugConsole(ex);
                throw ex;
            }

            return(FileName);
        }
예제 #14
0
 public string UploadFile(string folder, string filename, byte[] fileContents, FtpCredentials credentaials)
 {
     if (!string.IsNullOrEmpty(folder) && !string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(credentaials.password) && !string.IsNullOrEmpty(credentaials.Url) && !string.IsNullOrEmpty(credentaials.username))
     {
         try
         {
             List <string> existingfiles = ViewFile(folder, credentaials).ToList();
             List <string> listsamefile  = existingfiles.Where(a => a.Contains(filename)).ToList();
             string        responssse;
             if (listsamefile.Count == 0)
             {
                 string        ftp     = credentaials.Url + folder + "/" + filename;
                 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp);
                 //Enter FTP Server credentials.
                 request.Method        = WebRequestMethods.Ftp.UploadFile;
                 request.Credentials   = new NetworkCredential(credentaials.username, credentaials.password);
                 request.UsePassive    = true;
                 request.UseBinary     = true;
                 request.EnableSsl     = false;
                 request.ContentLength = fileContents.Length;
                 Stream requestStream = request.GetRequestStream();
                 requestStream.Write(fileContents, 0, fileContents.Length);
                 requestStream.Close();
                 FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                 Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
                 response.Close();
                 responssse = response.StatusDescription;
             }
             else
             {
                 responssse = "File Already Exists";
             }
             return(responssse);
         }
         catch (Exception exx)
         {
             return(exx.ToString());
         }
     }
     else
     {
         return("Please enter all the  credentials");
     }
 }