Example #1
1
    /* Download File */
    public string download(string remoteFile, string localFile)
    {
        string _result = null;

        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            /* Establish Return Communication with the FTP Server */
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            /* Get the FTP Server's Response Stream */
            ftpStream = ftpResponse.GetResponseStream();
            /* Open a File Stream to Write the Downloaded File */
            FileStream _localFileStream = new FileStream(localFile, FileMode.Create);
            /* Buffer for the Downloaded Data */
            byte[] _byteBuffer = new byte[bufferSize];
            int _bytesRead = ftpStream.Read(_byteBuffer, 0, bufferSize);
            /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
            //try
            //{
            while (_bytesRead > 0)
            {
                _localFileStream.Write(_byteBuffer, 0, _bytesRead);
                _bytesRead = ftpStream.Read(_byteBuffer, 0, bufferSize);
            }
            //}
            //catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            _localFileStream.Close();
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString());
            _result = ex.Message.ToString();
        }
        finally
        {
            /* Resource Cleanup */
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
        return _result;
    }
Example #2
1
	/* List Directory Contents in Detail (Name, Size, Created, etc.) */
	public string[] directoryListDetailed(string directory)
	{
		try
		{
			/* Create an FTP Request */
			ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
			/* Log in to the FTP Server with the User Name and Password Provided */
			ftpRequest.Credentials = new NetworkCredential(user, pass);
			/* When in doubt, use these options */
			ftpRequest.UseBinary = true;
			ftpRequest.UsePassive = true;
			ftpRequest.KeepAlive = true;
			/* Specify the Type of FTP Request */
			ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
			/* Establish Return Communication with the FTP Server */
			ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
			/* Establish Return Communication with the FTP Server */
			ftpStream = ftpResponse.GetResponseStream();
			/* Get the FTP Server's Response Stream */
			StreamReader ftpReader = new StreamReader(ftpStream);
			/* Store the Raw Response */
			string directoryRaw = null;
			/* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
			try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
			catch (Exception ex) { Console.WriteLine(ex.ToString()); }
			/* Resource Cleanup */
			ftpReader.Close();
			ftpStream.Close();
			ftpResponse.Close();
			ftpRequest = null;
			/* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
			try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
			catch (Exception ex) { Console.WriteLine(ex.ToString()); }
		}
		catch (Exception ex) { Console.WriteLine(ex.ToString()); }
		/* Return an Empty string Array if an Exception Occurs */
		return new string[] { "" };
	}
Example #3
1
    /* List Directory Contents File/Folder Name Only */
    public List<string> directoryListSimple(string directory)
    {
        List<string> _directoryList = null;
        string _chr = "|";

        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            /* Establish Return Communication with the FTP Server */
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            /* Establish Return Communication with the FTP Server */
            ftpStream = ftpResponse.GetResponseStream();

            /* Get the FTP Server's Response Stream */
            StreamReader _ftpReader = new StreamReader(ftpStream);
            /* Store the Raw Response */
            string _directoryRaw = null;
            /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
            while (_ftpReader.Peek() != -1)
            {
                _directoryRaw += _ftpReader.ReadLine() + _chr;
            }
            _ftpReader.Close();
            /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
            _directoryList = _directoryRaw.Split(_chr.ToCharArray()).ToList(); 
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString()); 
            _directoryList.Add(ex.Message.ToString()); 
        }
        finally
        {
            /* Resource Cleanup */
            ftpStream.Flush();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
        /* Return an Empty string Array if an Exception Occurs */
        return _directoryList;
    }
Example #4
0
	/* Upload File */
	public void upload(string remoteFile, string localFile)
	{
		try
		{
			/* Create an FTP Request */
			ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
			/* Log in to the FTP Server with the User Name and Password Provided */
			ftpRequest.Credentials = new NetworkCredential(user, pass);
			/* When in doubt, use these options */
			ftpRequest.UseBinary = true;
			ftpRequest.UsePassive = true;
			ftpRequest.KeepAlive = true;
			/* Specify the Type of FTP Request */
			ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
			/* Establish Return Communication with the FTP Server */
			ftpStream = ftpRequest.GetRequestStream();
			/* Open a File Stream to Read the File for Upload */
			FileStream localFileStream = new FileStream(localFile, FileMode.OpenOrCreate, FileAccess.Read);// 這邊要加 :  FileAccess.Read
			/* Buffer for the Downloaded Data */
			byte[] byteBuffer = new byte[bufferSize];
			int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
			
			if(bytesSent == 0)
			{
				Debug.LogError("Upload File size is Empty !");
			}
			/* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
			try
			{
				while (bytesSent != 0)
				{
					ftpStream.Write(byteBuffer, 0, bytesSent);
					bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
					Debug.Log(" ***** bytesSent siez = "+ bytesSent);
				}
			}
			catch (Exception ex) { 
				Debug.Log(" ***-1** file siez = ");
				
				Console.WriteLine(ex.ToString()); }
			/* Resource Cleanup */
			localFileStream.Close();
			ftpStream.Close();
			ftpRequest = null;
		}
		catch (Exception ex) { Console.WriteLine(ex.ToString()); }
		return;
	}
Example #5
0
        public void RunForFile(string filePath)
        {
            FileInfo fileInfo = new FileInfo(filePath);

            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(RequestURI.AbsoluteUri + fileInfo.Name);

            ftpRequest.Credentials   = LoginInfo;
            ftpRequest.UseBinary     = true;
            ftpRequest.ContentLength = fileInfo.Length;
            ftpRequest.Method        = WebRequestMethods.Ftp.UploadFile;

            byte[] fileBuffer = new byte[fileInfo.Length];

            try
            {
                using (FileStream fileStream = fileInfo.OpenRead())
                    using (Stream ftpStream = ftpRequest.GetRequestStream())
                    {
                        int numRead = fileStream.Read(fileBuffer, 0, fileBuffer.Length);
                        ftpStream.Write(fileBuffer, 0, numRead);
                    }
            } catch (Exception e) {
                Console.WriteLine("Failed to upload \"{0}\" - {1}", fileInfo.Name, e.Message);
                return;
            }

            FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();

            if (response.StatusCode != FtpStatusCode.ClosingData)
            {
                Console.WriteLine("Failed to upload \"{0}\" - {1}", fileInfo.Name, response.StatusDescription);
            }
            else
            {
                Console.WriteLine("Uploaded \"{0}\" succesfully.", fileInfo.Name);
            }
        }
Example #6
0
        /* Upload File */
        public void Upload(string remoteFile, string localFile)
        {
            /* Create an FTP Request */
            _ftpRequest = (FtpWebRequest)WebRequest.Create(Host + "/" + remoteFile);

            /* Log in to the FTP Server with the User Name and Password Provided */
            _ftpRequest.Credentials = new NetworkCredential(User, Pass);

            /* When in doubt, use these options */
            _ftpRequest.UseBinary  = true;
            _ftpRequest.UsePassive = Passive;
            _ftpRequest.KeepAlive  = KeepAlive;

            /* Specify the Type of FTP Request */
            _ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

            /* Establish Return Communication with the FTP Server */
            _ftpStream = _ftpRequest.GetRequestStream();

            /* Open a File Stream to Read the File for Upload */
            FileStream localFileStream = new FileStream(localFile, FileMode.Create);

            /* Buffer for the Downloaded Data */
            byte[] byteBuffer = new byte[_bufferSize];
            int    bytesSent  = localFileStream.Read(byteBuffer, 0, _bufferSize);

            /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
            while (bytesSent != 0)
            {
                _ftpStream.Write(byteBuffer, 0, bytesSent);
                bytesSent = localFileStream.Read(byteBuffer, 0, _bufferSize);
            }
            /* Resource Cleanup */
            localFileStream.Close();
            _ftpStream.Close();
            _ftpRequest = null;
        }
Example #7
0
        /// <param name="filter">The filter to apply when listing files (ex *.txt)</param>
        public List <string> ListDirectory(string filter)
        {
            List <string> files          = new List <string>();
            string        line           = "";
            string        remotePath     = _host + "/" + _remoteDirectory + "/" + filter;
            StreamReader  responseStream = null;;

            try
            {
                //Create a request for directory listing
                FtpWebRequest ftpWebRequest = CreateWebRequest(WebRequestMethods.Ftp.ListDirectory, remotePath);

                //Get a reference to the response stream
                FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                responseStream = new StreamReader(ftpWebResponse.GetResponseStream());

                while ((line = responseStream.ReadLine()) != null)
                {
                    files.Add(line);
                }
                OnMessageReceived(string.Format("Status: {0} {1} (FTP NLIST)", ftpWebResponse.StatusCode, ftpWebResponse.StatusDescription));
            }
            catch (WebException ex)
            {
                HandleException(ex);
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Close();
                }
            }

            //Return the list of files
            return(files);
        }
Example #8
0
        private bool DownloadFile(string imageName)
        {
            bool doneTask = false;

            try
            {
                FtpWebRequest requestDownload = (FtpWebRequest)WebRequest
                                                .Create($"ftp://{ftpConf.Host}:{ftpConf.Port}/{pathImgsConf.Source}/{pathImgsConf.DefaultImage}");
                requestDownload.Method      = WebRequestMethods.Ftp.DownloadFile;
                requestDownload.Credentials = new NetworkCredential(ftpConf.User, ftpConf.Pass);
                using (FtpWebResponse response = (FtpWebResponse)requestDownload.GetResponse())
                    using (Stream ftpStream = response.GetResponseStream())
                        using (Stream fileStream = File.Create($@"{pathImgsConf.Target}\{imageName}.jpg"))
                        {
                            ftpStream.CopyTo(fileStream);
                            activityTxt.Invoke((Action) delegate
                            {
                                activityTxt.AppendText("Image saved" + "\r\n");
                            });
                            response.Close();
                            DeleteFile();
                            doneTask = true;
                        }
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    activityTxt.Invoke((Action) delegate
                    {
                        activityTxt.AppendText("File not exist" + "\r\n");
                    });
                }
            }
            return(doneTask);
        }
        public void DownloadFtpFiles(string ftpServerIP, string ftpPath)
        {
            try
            {
                string uriPath = "ftp://" + ftpServerIP + "/" + ftpPath + "/";
                // Get the object used to communicate with the server.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uriPath);
                request.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
                request.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);
                FtpWebResponse response       = (FtpWebResponse)request.GetResponse();
                Stream         responseStream = response.GetResponseStream();
                StreamReader   reader         = new StreamReader(responseStream);

                while (!reader.EndOfStream)
                {
                    String fileAttribute = reader.ReadLine();
                    int    idxLastSpace  = fileAttribute.LastIndexOf(" ");
                    String fileName      = fileAttribute.Substring(idxLastSpace + 1);

                    string destPathFile = _appPath + "\\" + fileName;

                    //if (!File.Exists(destPathFile))
                    //{
                    DownloadFile(ftpServerIP, ftpPath, fileName);
                    //}
                }

                Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

                reader.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("AutoRunProcess 执行失敗:" + ex.Message);
            }
        }
Example #10
0
        //从ftp服务器上下载文件的功能
        public int Download(string fileName)
        {
            FtpWebRequest reqFTP;

            try
            {
                string     filePath     = Application.StartupPath;
                FileStream outputStream = new FileStream(filePath + "\\ssr-win\\" + fileName, FileMode.Create);
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
                reqFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.UsePassive  = false;
                FtpWebResponse response   = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream  = response.GetResponseStream();
                long           cl         = response.ContentLength;
                int            bufferSize = 2048;
                int            readCount;
                byte[]         buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
                return(1);
            }
            catch (Exception ex)
            {
                return(-1);

                throw ex;
            }
        }
Example #11
0
    private void UploadFile(string newFileName)
    {
        try
        {
            string url      = GetUrlString(newFileName);
            string filepath = Application.dataPath + "/StreamingAssets/" + newFileName;

            FtpWebRequest request        = CreatFtpWebRequest(url, WebRequestMethods.Ftp.UploadFile);
            Stream        responseStream = request.GetRequestStream();

            FileStream fs = File.OpenRead(filepath);
            //FileStream fileStream = File.Create(url+"/testFile.txt");
            int    buflength = 8196;
            byte[] buffer    = new byte[buflength];
            int    bytesRead = 1;

            while (bytesRead != 0)
            {
                bytesRead = fs.Read(buffer, 0, buflength);
                responseStream.Write(buffer, 0, bytesRead);
            }

            responseStream.Close();
            if (ShowFtpFileAndDirectory() == true)
            {
                Debug.Log("Upload success!");
            }
            else
            {
                Debug.Log("Upload failed!");
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message);
        }
    }
Example #12
0
        public bool UploadFileToFTPFromWEBCLIENT(string ftpurl, string ftpusername, string ftppassword, byte[] inputStream, string strFTPFilePath)
        {
            bool upldStatus = false;

            try
            {
                ftpRequest             = (FtpWebRequest)FtpWebRequest.Create(ftpurl + strFTPFilePath);
                ftpRequest.Credentials = new NetworkCredential(ftpusername, ftppassword);

                ftpRequest.UseBinary  = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive  = false;
                ftpRequest.Method     = WebRequestMethods.Ftp.UploadFile;

                // Stream straemIn = inputStream;
                byte[] buffer = inputStream;
                //straemIn.Read(buffer, 0, buffer.Length);
                //straemIn.Close();

                ftpStream = ftpRequest.GetRequestStream();
                ftpStream.Write(buffer, 0, buffer.Length);
                ftpStream.Close();

                FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();

                //response.StatusDescription

                response.Close();
                upldStatus = true;
                ftpRequest = null;
            }
            catch (Exception)
            {
            }

            return(upldStatus);
        }
Example #13
0
        public void DownloadFile(string ftpSourceFileUrl, string localDestinationFilePath, bool enableSsl)
        {
            FtpWebRequest request = WebRequest.Create(ftpSourceFileUrl) as FtpWebRequest;

            if (request == null)
            {
                throw new InvalidCastException(string.Format("Could not get {0} for {1}.", typeof(FtpWebRequest).FullName, ftpSourceFileUrl));
            }
            request.Method           = WebRequestMethods.Ftp.DownloadFile;
            request.KeepAlive        = _keepAlive;
            request.Timeout          = _timeout;
            request.ReadWriteTimeout = _readWriteTimeout;
            request.Credentials      = _credentials;
            request.EnableSsl        = enableSsl;
            if (File.Exists(localDestinationFilePath))
            {
                File.Delete(localDestinationFilePath);
            }
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (FileStream fileStream = File.Create(localDestinationFilePath))
                    {
                        byte[] buffer = new byte[32 * 1024];
                        int    readLength;
                        while ((readLength = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fileStream.Write(buffer, 0, readLength);
                        }
                        fileStream.Close();
                    }
                    responseStream.Close();
                }
                response.Close();
            }
        }
Example #14
0
        public bool Ping()
        {
            var           results            = false;
            FtpWebRequest request            = CreateRequest(WebRequestMethods.Ftp.PrintWorkingDirectory);
            string        ErrorMessageHeader = string.Format(@"Ping <{0}>", this.FtpUri);

            try
            {
                using (var response = (FtpWebResponse)request.GetResponse())
                {
                    var responseStream = response.GetResponseStream();
                    if (null != responseStream)
                    {
                        results = true;
                    }
                    response.Close();
                }
            }
            catch (WebException webex)
            {
                _lastexception    = webex;
                _lastErrorMessage = string.Format(ErrorMessageFormat,
                                                  ErrorMessageHeader,
                                                  null != webex.InnerException ? webex.InnerException.Message : webex.Message,
                                                  webex.StackTrace);
            }
            catch (Exception ex)
            {
                _lastexception    = ex;
                _lastErrorMessage = string.Format(ErrorMessageFormat,
                                                  ErrorMessageHeader,
                                                  null != ex.InnerException ? ex.InnerException.Message : ex.Message,
                                                  ex.StackTrace);
            }

            return(results);
        }
Example #15
0
        private int ConnectAndUpload(string fileName, string filePath, string serverPath, bool message)
        {
            string completeServerPath = serverPath;
            string password           = Password;
            string username           = Username;

            try
            {
                //Create FTP request
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(completeServerPath + fileName);
                request.Method      = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive  = true;
                request.UseBinary   = true;
                request.KeepAlive   = false;
                //Load the file
                FileStream stream = File.OpenRead(@filePath);
                byte[]     buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Close();
                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
                if (message)
                {
                    MessageBox.Show("Success, The file is now uploaded at:  /n" + completeServerPath + fileName, "Success!");
                }
                return(1);
            }
            catch (WebException re)
            {
                String status = ((FtpWebResponse)re.Response).StatusDescription;
                MessageBox.Show(status, "ERROR");
                return(0);
            }
        }
Example #16
0
        /// <summary>
        /// ftp方式上传
        /// </summary>
        public static int Upload(string filePath, string filename, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            FileInfo      fileInf = new FileInfo(filePath + "\\" + filename);
            string        uri     = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));
            try
            {
                reqFTP.Credentials   = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive     = false;
                reqFTP.Method        = WebRequestMethods.Ftp.UploadFile;
                reqFTP.UseBinary     = true;
                reqFTP.ContentLength = fileInf.Length;
                int        buffLength = 2048;
                byte[]     buff       = new byte[buffLength];
                int        contentLen;
                FileStream fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                Stream strm = reqFTP.GetRequestStream();

                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
                return(0);
            }
            catch
            {
                reqFTP.Abort();
                return(-2);
            }
        }
Example #17
0
        public bool DownloadFile(string url, string savePath)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
                request.Proxy       = Options.ProxySettings;
                request.Method      = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
                request.KeepAlive   = false;
                request.UsePassive  = !Options.Account.IsActive;

                using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                        using (Stream stream = response.GetResponseStream())
                        {
                            ProgressManager progress = new ProgressManager(stream.Length);

                            byte[] buffer = new byte[BufferSize];
                            int    bytesRead;

                            while ((bytesRead = stream.Read(buffer, 0, BufferSize)) > 0)
                            {
                                fileStream.Write(buffer, 0, bytesRead);
                                progress.UpdateProgress(bytesRead);
                                OnProgressChanged(progress);
                            }
                        }

                WriteOutput(string.Format("DownloadFile: {0} -> {1}", url, savePath));
                return(true);
            }
            catch (Exception ex)
            {
                WriteOutput(string.Format("Error: {0} - DownloadFile: {1} -> {2}", ex.Message, url, savePath));
            }
            return(false);
        }
Example #18
0
 /* Get the Date/Time a File was Created */
 public string getFileCreatedDateTime(string fileName)
 {
     try
     {
         /* Create an FTP Request */
         ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
         /* Log in to the FTP Server with the User Name and Password Provided */
         ftpRequest.Credentials = new NetworkCredential(user, pass);
         /* When in doubt, use these options */
         ftpRequest.UseBinary  = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive  = true;
         /* Specify the Type of FTP Request */
         ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
         /* Establish Return Communication with the FTP Server */
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         /* Establish Return Communication with the FTP Server */
         ftpStream = ftpResponse.GetResponseStream();
         /* Get the FTP Server's Response Stream */
         StreamReader ftpReader = new StreamReader(ftpStream);
         /* Store the Raw Response */
         string fileInfo = null;
         /* Read the Full Response Stream */
         try { fileInfo = ftpReader.ReadToEnd(); }
         catch (Exception ex) { Console.WriteLine(ex.ToString()); }
         /* Resource Cleanup */
         ftpReader.Close();
         ftpStream.Close();
         ftpResponse.Close();
         ftpRequest = null;
         /* Return File Created Date Time */
         return(fileInfo);
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     /* Return an Empty string Array if an Exception Occurs */
     return("");
 }
Example #19
0
        /// <summary>
        /// Uploads a file to an FTP site
        /// </summary>
        /// <param name="sourceFilePath">Local file</param>
        /// <param name="destinationFileUrl">Destination Url</param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string UploadFile(string sourceFilePath, string destinationFileUrl, string username = Constants.FTP.Username, string password = Constants.FTP.Password)
        {
            string output;

            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destinationFileUrl);

            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential(username, password);

            // Copy the contents of the file to the request stream.
            byte[] fileContents;
            using (StreamReader sourceStream = new StreamReader(sourceFilePath))
            {
                fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            }

            //Get the length or size of the file
            request.ContentLength = fileContents.Length;

            //Write the file to the stream on the server
            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(fileContents, 0, fileContents.Length);
            }

            //Send the request
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                output = $"Upload File Complete, status {response.StatusDescription}";
            }
            Thread.Sleep(Constants.FTP.OperationPauseTime);

            return(output);
        }
Example #20
0
        private string[] GetFileList(string path, string WRMethods)
        {
            StringBuilder result = new StringBuilder();

            try
            {
                FtpWebRequest reqFTP = this.Connect(path);//建立FTP连接
                reqFTP.Method    = WRMethods;
                reqFTP.KeepAlive = false;
                WebResponse  response = reqFTP.GetResponse();
                StreamReader reader   = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
                string       line     = reader.ReadLine();

                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }

                // to remove the trailing '' ''
                if (result.ToString() != "")
                {
                    result.Remove(result.ToString().LastIndexOf("\n"), 1);
                }
                reader.Close();
                response.Close();
                return(result.ToString().Split('\n'));
            }

            catch (Exception ex)
            {
                Log.WriteLine("获取文件列表失败。原因: " + ex.Message);

                throw ex;
            }
        }
Example #21
0
        private static FtpWebRequest GetFtpWebRequest(string url, string userName, string password, string method, bool keepAlive, bool forceBinary)
        {
            if (!url.StartsWith("ftp://"))
            {
                throw new ArgumentException("The URL \n" + url + "\ndoes not begin with \n\"ftp://\"  \nThis is a requirement");
            }

            Uri uri = new Uri(url, UriKind.Absolute);


            FtpWebRequest ftpclientRequest = WebRequest.Create(uri) as FtpWebRequest;

            ftpclientRequest.KeepAlive = keepAlive;

            ftpclientRequest.Method = method;
            switch (method)
            {
            case WebRequestMethods.Ftp.ListDirectoryDetails:
                ftpclientRequest.Proxy = null;
                break;

            case WebRequestMethods.Ftp.DownloadFile:
                ftpclientRequest.UseBinary = forceBinary;
                break;

            case WebRequestMethods.Ftp.UploadFile:
                ftpclientRequest.UsePassive = true;

                ftpclientRequest.UseBinary = true;
                break;
            }


            ftpclientRequest.Credentials = new NetworkCredential(userName, password);

            return(ftpclientRequest);
        }
Example #22
0
        private void FtpRename(string oldName, string newName, bool isFile)
        {
            FtpWebResponse ftpResp = null;

            try
            {
                string        path       = this._ftpPath + "/" + oldName;
                FtpWebRequest ftpRequest = this.GetFtpRequest(path, WebRequestMethods.Ftp.Rename, true);
                ftpRequest.RenameTo = newName;
                ftpResp             = (FtpWebResponse)ftpRequest.GetResponse();

                if (ftpResp.StatusCode == FtpStatusCode.FileActionOK)
                {
                    this.GetFilesFromFTPServer(this._ftpPath);
                }
                else
                {
                    string message = String.Format("{0}\nКод: {1}", "Не удалось выполнить операцию", ftpResp.StatusCode);
                    MessageBox.Show(message, "Операция на FTP сервере", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (WebException we)
            {
                MessageBox.Show(we.Message, "Операция на FTP сервере", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "Ошибка в приложении", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (ftpResp != null)
                {
                    ftpResp.Close();
                }
            }
        }
        private bool TryToConnect(out string status)
        {
            status = null;
            string rootFolder = FTPSettings.Server + FTPSettings.InternalFTPFolder;

            FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(rootFolder);

            requestDir.Method      = WebRequestMethods.Ftp.MakeDirectory;
            requestDir.Credentials = new NetworkCredential(FTPSettings.Login, FTPSettings.Password);
            requestDir.UsePassive  = true;
            requestDir.UseBinary   = true;
            requestDir.KeepAlive   = false;
            try
            {
                WebResponse response  = requestDir.GetResponse();
                Stream      ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
                return(true);
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    response.Close();
                    return(true);
                }
                else
                {
                    response.Close();
                    status = ex.Message;
                    return(false);
                }
            }
        }
Example #24
0
        /// <summary>
        /// 上传
        /// </summary>
        public bool Upload(string filename)
        {
            try
            {
                FileInfo      fileInf = new FileInfo(filename);
                FtpWebRequest reqFTP;
                reqFTP               = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
                reqFTP.Credentials   = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method        = WebRequestMethods.Ftp.UploadFile;
                reqFTP.KeepAlive     = false;
                reqFTP.UseBinary     = true;
                reqFTP.ContentLength = fileInf.Length;
                int    buffLength = 2048;
                byte[] buff       = new byte[buffLength];
                int    contentLen;
                using (FileStream fs = fileInf.OpenRead())
                {
                    Stream strm = reqFTP.GetRequestStream();
                    contentLen = fs.Read(buff, 0, buffLength);
                    while (contentLen != 0)
                    {
                        strm.Write(buff, 0, contentLen);
                        contentLen = fs.Read(buff, 0, buffLength);
                    }
                    strm.Close();
                    fs.Close();
                }

                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteLine(string.Format("{0}-{1}{2}", ex.Message, ftpURI, filename));
                //throw new Exception(ex.Message);
                return(false);
            }
        }
Example #25
0
        public MsCrmResult SendFile(string filePath, string fileName)
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_ftpUrl + "/isgyodata/" + fileName);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                // This example assumes the FTP site uses anonymous logon.
                request.Credentials = new NetworkCredential(_userName, _password);

                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(filePath);

                byte[] fileContents = Encoding.Default.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                returnValue.Result  = string.Format("Upload File Complete, status {0}", response.StatusDescription);
                returnValue.Success = true;

                response.Close();
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }

            return(returnValue);
        }
Example #26
0
        public void Download(string ftp_url, string fileName, BackgroundWorker bgk)
        {
            int bytesRead = 0;

            byte[] buffer = new byte[2048];

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

            request.Credentials = new NetworkCredential("portalsk", "fra@1705");

            //System.Windows.MessageBox.Show(FileSize(ftp_url).ToString());
            int filesize = FileSize(ftp_url);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

            Stream     reader     = request.GetResponse().GetResponseStream();
            FileStream fileStream = new FileStream(fileName, FileMode.Create);

            int totalReadBytesCount = 0;

            while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
            {
                //System.Threading.Thread.Sleep(10);

                if (bytesRead == 0)
                {
                    break;
                }

                fileStream.Write(buffer, 0, bytesRead);
                totalReadBytesCount += bytesRead;
                var progress = totalReadBytesCount * 100.0 / filesize;
                bgk.ReportProgress((int)progress);
            }

            fileStream.Close();
        }
Example #27
0
        public static string InsertIntoFTPFile(string center)
        {
            try
            {
                string fileName = Helper.GetSetting("UploadFileName");
                ftpRequest             = (FtpWebRequest)WebRequest.Create(host + "/A" + center + "/" + fileName);
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                ftpRequest.Method      = WebRequestMethods.Ftp.UploadFile;

                // Copy the contents of the file to the request stream.
                StreamReader sourceStream = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/NewBeneDetails/A" + center + "/UP_CART.txt"));
                byte[]       fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                ftpRequest.ContentLength = fileContents.Length;

                Stream requestStream = ftpRequest.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
                Helper.FileLogging("Upload Data Completed, status {0}" + response.StatusDescription);
                Helper.FileLogging("Upload Data Completed, status {0} : " + response.StatusCode);
                response.Close();
                return("000");
            }
            catch (Exception ex)
            {
                if (ex.InnerException == null)
                {
                    return(ex.Message);
                }
                else
                {
                    return(ex.InnerException.Message);
                }
            }
        }
Example #28
0
        public void delete(string fileName)
        {
            try
            {
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format(baseUrl, fileName));
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential(userName, password);

                ftpRequest.UseBinary  = true; //because Windows
                ftpRequest.UsePassive = true; //when in doubt...
                ftpRequest.KeepAlive  = true; //when in doubt...
                ftpRequest.EnableSsl  = true;
                //specify that we're deleting.
                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                //Cleanup
                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                //Clean up even though we failed
                if (ftpRequest != null)
                {
                    ftpRequest = null;
                }
                if (ftpResponse != null)
                {
                    ftpResponse.Close();
                }

                Console.WriteLine(ex.ToString()); //This is obnoxious.
            }
            return;
        }
Example #29
0
        static void Main(string[] args)
        {
            //API Data
            string FullPathUrl = @"https://webapibasicsstudenttracker.azurewebsites.net/api/students";
            //string localUploadFilePath = @"C:\Users\Owner\Desktop\IES\info.docx";
            //string remoteUploadFileDestination = "/200425224 Saba Sultana/info.docx";


            //Download the API data
            string         json        = new System.Net.WebClient().DownloadString(FullPathUrl);
            List <Student> studentList = JsonConvert.DeserializeObject <List <Student> >(json);


            Console.WriteLine();

            //Adding Data to Document.
            string strDoc = @$ "{Constants.Student.ContentFolder}" + "\\info.docx";

            //string strTxt = RO;

            //Creating Word Document
            CreateWordprocessingDocument(@$ "{Constants.Student.ContentFolder}" + "\\info.docx");
            OpenAndAddTextToWordDocument(strDoc, studentList);
            //Creating Excel Document
            Models.Excel.CreateSpreadsheetWorkbook(@$ "{Constants.Student.ContentFolder}" + "\\info.xlsx");
            Models.Excel.InsertText(@$ "{Constants.Student.ContentFolder}" + "\\info.xlsx", studentList);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Constants.FTP.BaseUrl);

            request.Method      = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(Constants.FTP.UserName, Constants.FTP.Password);
            string imageFilePath = Constants.FTP.myFtpFolder + "/" + Constants.Student.MyImageFileName;
            var    imageBytes    = Ftp.DownloadFileBytes(imageFilePath);
            Image  image         = Imaging.byteArrayToImage(imageBytes);

            Console.WriteLine("Downloaded image file:");
        }
Example #30
0
 /// <summary>
 /// 下载
 /// </summary>
 public void Download(string filePath, string fileName)
 {
     try
     {
         if (!Directory.Exists(filePath))
         {
             Directory.CreateDirectory(filePath);
         }
         using (FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create))
         {
             FtpWebRequest reqFTP;
             reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
             reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
             reqFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
             reqFTP.UseBinary   = true;
             FtpWebResponse response   = (FtpWebResponse)reqFTP.GetResponse();
             Stream         ftpStream  = response.GetResponseStream();
             long           cl         = response.ContentLength;
             int            bufferSize = 2048;
             int            readCount;
             byte[]         buffer = new byte[bufferSize];
             readCount = ftpStream.Read(buffer, 0, bufferSize);
             while (readCount > 0)
             {
                 outputStream.Write(buffer, 0, readCount);
                 readCount = ftpStream.Read(buffer, 0, bufferSize);
             }
             ftpStream.Close();
             //outputStream.Close();
             response.Close();
         }
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Example #31
0
        /// <summary>
        /// FTP 연결 테스트
        /// </summary>
        /// <param name="url"></param>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool TestConnection()
        {
            int rCount = 3;

_retry:

            var avail = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

            if (!avail)
            {
                Thread.Sleep(5000);
                goto _retry;
            }

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + m_Server);
                request.Timeout     = 1000 * 5;
                request.Method      = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = Credentials;
                request.GetResponse();
            }
            catch (WebException ex)
            {
                rCount--;
                if (rCount <= 0)
                {
                    return(false);
                }
                else
                {
                    goto _retry;
                }
            }

            return(true);
        }
Example #32
0
        private void Download(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;

            try
            {
                //filePath = <<The full path where the file is to be created.>>,
                //fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
                reqFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response   = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream  = response.GetResponseStream();
                long           cl         = response.ContentLength;
                int            bufferSize = 2048;
                int            readCount;
                byte[]         buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #33
0
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="filename"></param>
        public void Upload(string filename)
        {
            FileInfo      fileInf = new FileInfo(filename);
            string        uri     = ftpURI + fileInf.Name;
            FtpWebRequest reqFTP;

            reqFTP               = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Credentials   = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive     = false;
            reqFTP.Method        = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary     = true;
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;

            byte[]     buff = new byte[buffLength];
            int        contentLen;
            FileStream fs = fileInf.OpenRead();

            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
                //int c = 0;
                //Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message);
            }
        }
        private void Upload(string remoteFile, string localFile)
        {
            try
            {
                _ftpRequest             = (FtpWebRequest)WebRequest.Create($"{_host}/{remoteFile}");
                _ftpRequest.Credentials = new NetworkCredential(_username, _password);
                _ftpRequest.UseBinary   = true;
                _ftpRequest.UsePassive  = true;
                _ftpRequest.KeepAlive   = true;
                _ftpRequest.Method      = WebRequestMethods.Ftp.UploadFile;
                _ftpStream = _ftpRequest.GetRequestStream();
                var localFileStream = new FileStream(localFile, FileMode.Open);
                var byteBuffer      = new byte[BufferSize];
                var bytesSent       = localFileStream.Read(byteBuffer, 0, BufferSize);
                try
                {
                    while (bytesSent != 0)
                    {
                        _ftpStream.Write(byteBuffer, 0, bytesSent);
                        bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                localFileStream.Close();
                _ftpStream.Close();
                _ftpRequest = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
Example #35
0
    /* Get the Size of a File */
    public string getFileSize(string fileName)
    {
        string _result = null;
        string _fileInfo = null;

        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
            /* Establish Return Communication with the FTP Server */
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            /* Establish Return Communication with the FTP Server */
            ftpStream = ftpResponse.GetResponseStream();
            /* Get the FTP Server's Response Stream */
            StreamReader _ftpReader = new StreamReader(ftpStream);
            /* Store the Raw Response */

            /* Read the Full Response Stream */
            while (_ftpReader.Peek() != -1)
            {
                _fileInfo = _ftpReader.ReadToEnd();
            }
            _ftpReader.Close();

            /* Return File Size */
            _result = _fileInfo;
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString()); 
            _result = ex.Message.ToString();
        }
        finally
        {
            /* Resource Cleanup */
            
            ftpStream.Flush();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
        return _result;
    }
Example #36
0
        private static MemoryStream DoOldStyleAsync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                IAsyncResult ar = request.BeginGetRequestStream(null, null);
                ar.AsyncWaitHandle.WaitOne();
                Stream requestStream = request.EndGetRequestStream(ar);
                requestBody.CopyTo(requestStream);
                requestStream.Close();
            }

            IAsyncResult ar2 = request.BeginGetResponse(null, null);
            ar2.AsyncWaitHandle.WaitOne();
            FtpWebResponse response = (FtpWebResponse)request.EndGetResponse(ar2);

            MemoryStream responseBody = new MemoryStream();
            response.GetResponseStream().CopyTo(responseBody);
            response.Close();

            return responseBody;
        }
Example #37
0
        private static async Task<MemoryStream> DoAsync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                Stream requestStream = await request.GetRequestStreamAsync();
                await requestBody.CopyToAsync(requestStream);
                requestStream.Close();
            }

            MemoryStream responseBody = new MemoryStream();
            FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
            await response.GetResponseStream().CopyToAsync(responseBody);
            response.Close();

            return responseBody;
        }
Example #38
0
	/* Create a New Directory on the FTP Server */
	public void createDirectory(string newDirectory)
	{
		try
		{
			/* Create an FTP Request */
			ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory);
			/* Log in to the FTP Server with the User Name and Password Provided */
			ftpRequest.Credentials = new NetworkCredential(user, pass);
			/* When in doubt, use these options */
			ftpRequest.UseBinary = true;
			ftpRequest.UsePassive = true;
			ftpRequest.KeepAlive = true;
			/* Specify the Type of FTP Request */
			ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
			/* Establish Return Communication with the FTP Server */
			ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
			/* Resource Cleanup */
			ftpResponse.Close();
			ftpRequest = null;
		}
		catch (Exception ex) { Console.WriteLine(ex.ToString()); }
		return;
	}
Example #39
0
        private static MemoryStream DoSync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                Stream requestStream = request.GetRequestStream();
                requestBody.CopyTo(requestStream);
                requestStream.Close();
            }

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            MemoryStream responseBody = new MemoryStream();
            response.GetResponseStream().CopyTo(responseBody);
            response.Close();

            return responseBody;
        }
Example #40
0
    /* Upload File */
    public string upload(string remoteFile, string localFile)
    {
        string _result = null;

        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + host + "/" + remoteFile);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            /* Establish Return Communication with the FTP Server */
            ftpStream = ftpRequest.GetRequestStream();
            /* Open a File Stream to Read the File for Upload */
            /* use openorcreate as just open will overwrite the file if it already exists */
            FileStream _localFileStream = new FileStream(localFile, FileMode.OpenOrCreate);
            /* Buffer for the Downloaded Data */
            byte[] _byteBuffer = new byte[bufferSize];
            int _bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize);
            /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
            //try
            //{
            while (_bytesSent != 0)
            {
                ftpStream.Write(_byteBuffer, 0, _bytesSent);
                _bytesSent = _localFileStream.Read(_byteBuffer, 0, bufferSize);
            }
            //}
            //catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            
            _localFileStream.Close();
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString()); 
            _result = ex.Message.ToString();
        }
        finally
        {
            /* Resource Cleanup */
            ftpStream.Flush();
            ftpStream.Close();
            ftpRequest = null;
        }
        return _result;
    }
Example #41
0
    /* Rename File */
    public string rename(string currentFileNameAndPath, string newFileName)
    {
        string _result = null;

        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + currentFileNameAndPath);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.Rename;
            /* Rename the File */
            ftpRequest.RenameTo = newFileName;
            /* Establish Return Communication with the FTP Server */
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString());
            _result = ex.Message.ToString();
        }
        finally
        {
            /* Resource Cleanup */
            ftpResponse.Close();
            ftpRequest = null;
        }
        return _result;
    }
Example #42
0
	/* Get the Size of a File */
	public string getFileSize(string fileName)
	{
		try
		{
			/* Create an FTP Request */
			ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
			/* Log in to the FTP Server with the User Name and Password Provided */
			ftpRequest.Credentials = new NetworkCredential(user, pass);
			/* When in doubt, use these options */
			ftpRequest.UseBinary = true;
			ftpRequest.UsePassive = true;
			ftpRequest.KeepAlive = true;
			/* Specify the Type of FTP Request */
			ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
			/* Establish Return Communication with the FTP Server */
			ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
			/* Establish Return Communication with the FTP Server */
			ftpStream = ftpResponse.GetResponseStream();
			/* Get the FTP Server's Response Stream */
			StreamReader ftpReader = new StreamReader(ftpStream);
			/* Store the Raw Response */
			string fileInfo = null;
			/* Read the Full Response Stream */
			try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } }
			catch (Exception ex) { Console.WriteLine(ex.ToString()); }
			/* Resource Cleanup */
			ftpReader.Close();
			ftpStream.Close();
			ftpResponse.Close();
			ftpRequest = null;
			/* Return File Size */
			return fileInfo;
		}
		catch (Exception ex) { Console.WriteLine(ex.ToString()); }
		/* Return an Empty string Array if an Exception Occurs */
		return "";
	}