Exemplo n.º 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;
    }
Exemplo n.º 2
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;
    }
Exemplo n.º 3
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[] { "" };
	}
Exemplo n.º 4
0
            public IList <IActivityIOPath> ListDirectoryStandardFtp(IActivityIOPath src)
            {
                var result = new List <IActivityIOPath>();

                try
                {
                    var request = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(src.Path));
                    request.Method    = WebRequestMethods.Ftp.ListDirectory;
                    request.UseBinary = true;
                    request.KeepAlive = false;
                    request.EnableSsl = EnableSsl(src);

                    if (src.Username != string.Empty)
                    {
                        request.Credentials = new NetworkCredential(src.Username, src.Password);
                    }

                    if (src.IsNotCertVerifiable)
                    {
                        ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
                    }

                    using (FtpWebResponse response = request.GetResponse() as FtpWebResponse)
                    {
                        using (Stream responseStream = response?.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (StreamReader reader = new StreamReader(responseStream))
                                {
                                    while (!reader.EndOfStream)
                                    {
                                        var uri = BuildValidPathForFtp(src, reader.ReadLine());
                                        result.Add(ActivityIOFactory.CreatePathFromString(uri, src.Username, src.Password, true, src.PrivateKeyFile));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (WebException webEx)
                {
                    var webResponse = webEx.Response as FtpWebResponse;
                    {
                        if (webResponse?.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                        {
                            throw new DirectoryNotFoundException(string.Format(ErrorResource.DirectoryNotFound, src.Path));
                        }
                        throw;
                    }
                }
                catch (Exception ex)
                {
                    Dev2Logger.Error(this, ex, GlobalConstants.WarewolfError);
                    throw;
                }

                return(result);
            }
Exemplo n.º 5
0
        private KeyValuePair <FtpStatusCode, string> Ftp(string method, string name, Func <byte[]> dataFunc = null)
        {
            FtpWebResponse response     = null;
            string         responseText = null;

            _flashExpiry = DateTime.Now.AddSeconds(5);
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));

            try
            {
                var request = (FtpWebRequest)WebRequest.Create(Combine(_settings.FtpUrl, _settings.FtpPath, name));

                request.UseBinary   = true;
                request.Method      = method;
                request.KeepAlive   = false;
                request.Credentials = new NetworkCredential(
                    _settings.Username,
                    Encoding.UTF8.GetString(Convert.FromBase64String(_settings.Password)));

                if (dataFunc != null)
                {
                    using (var writer = request.GetRequestStream())
                    {
                        var data = dataFunc();
                        writer.Write(data, 0, data.Length);
                        writer.Close();
                    }
                }

                response = request.GetResponse() as FtpWebResponse;

                using (var stream = response?.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        responseText = reader.ReadToEnd();
                    }

                Log($"{method} {name} success");
            }
            catch (WebException ex)
            {
                response = ex.Response as FtpWebResponse;
                Log($"{method} {name} failure - {ex.Message}");
            }
            catch (Exception ex)
            {
                Log($"{method} {name} failure - {ex.Message}");
            }

            return(new KeyValuePair <FtpStatusCode, string>(response?.StatusCode ?? FtpStatusCode.Undefined, responseText));
        }
Exemplo n.º 6
0
        /// <summary>
        /// 改名
        /// </summary>
        /// <param name="currentFilename"></param>
        /// <param name="newFilename"></param>
        public void Rename(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;

            try
            {
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
                reqFTP.Method      = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo    = newFilename;
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
                reqFTP.Proxy       = null;
                FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                log.Error("Rename File from: " + currentFilename + " to: " + newFilename + "error.", ex);
                throw new TechnicalException("Rename File from: " + currentFilename + " to: " + newFilename + "error.", ex);
            }
        }
Exemplo n.º 7
0
        private long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long          fileSize = 0;

            try
            {
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename));
                reqFTP.Method      = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(fileSize);
        }
Exemplo n.º 8
0
        // Token: 0x060000A3 RID: 163 RVA: 0x0000A53C File Offset: 0x0000873C
        public long GetFileSize(string filename)
        {
            long result = 0L;

            try
            {
                FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri(this.ftpURI + filename));
                ftpWebRequest.Method      = "SIZE";
                ftpWebRequest.UseBinary   = true;
                ftpWebRequest.UsePassive  = false;
                ftpWebRequest.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
                FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                Stream         responseStream = ftpWebResponse.GetResponseStream();
                result = ftpWebResponse.ContentLength;
                responseStream.Close();
                ftpWebResponse.Close();
            }
            catch (WebException ex)
            {
                string statusDescription = ((FtpWebResponse)ex.Response).StatusDescription;
                result = 1024L;
            }
            return(result);
        }
Exemplo n.º 9
0
        public void DownloadFile(string path, string fileName)
        {
            ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + Host + path + "/" + fileName);

            ftpRequest.Credentials = new NetworkCredential(User, Password);
            ftpRequest.Method      = WebRequestMethods.Ftp.DownloadFile;

            ftpRequest.EnableSsl = UseSSL;
            FileStream downloadedFile = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);

            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            Stream responseStream = ftpResponse.GetResponseStream();

            byte[] buffer = new byte[1024];
            int    size   = 0;

            while ((size = responseStream.Read(buffer, 0, 1024)) > 0)
            {
                downloadedFile.Write(buffer, 0, size);
            }
            ftpResponse.Close();
            downloadedFile.Close();
            responseStream.Close();
        }
Exemplo n.º 10
0
 public bool Download(string remoteFile, string localFile, bool deleteOld = true)
 {
     try
     {
         ftpRequest             = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
         ftpRequest.Credentials = new NetworkCredential(user, pass);
         ftpRequest.UseBinary   = true;
         ftpRequest.UsePassive  = true;
         ftpRequest.KeepAlive   = true;
         ftpRequest.Method      = WebRequestMethods.Ftp.DownloadFile;
         ftpResponse            = (FtpWebResponse)ftpRequest.GetResponse();
         ftpStream = ftpResponse.GetResponseStream();
         FileStream localFileStream = new FileStream(localFile, FileMode.Create);
         if (!deleteOld && File.Exists(localFile))
         {
             throw new Exception("Can not create file '" + localFile + "'. The file is exist");
         }
         byte[] byteBuffer = new byte[bufferSize];
         int    bytesRead  = ftpStream.Read(byteBuffer, 0, bufferSize);
         while (bytesRead > 0)
         {
             localFileStream.Write(byteBuffer, 0, bytesRead);
             bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
         }
         localFileStream.Close();
         ftpStream.Close();
         ftpResponse.Close();
         ftpRequest = null;
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
         return(false);
     }
 }
Exemplo n.º 11
0
 // Token: 0x0600009C RID: 156 RVA: 0x00009FB4 File Offset: 0x000081B4
 public void RemoveDirectory(string folderName)
 {
     try
     {
         string        uriString     = this.ftpURI + folderName;
         FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri(uriString));
         ftpWebRequest.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword);
         ftpWebRequest.Method      = "RMD";
         ftpWebRequest.UsePassive  = false;
         string         empty          = string.Empty;
         FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
         long           contentLength  = ftpWebResponse.ContentLength;
         Stream         responseStream = ftpWebResponse.GetResponseStream();
         StreamReader   streamReader   = new StreamReader(responseStream);
         streamReader.ReadToEnd();
         streamReader.Close();
         responseStream.Close();
         ftpWebResponse.Close();
     }
     catch (Exception ex)
     {
         throw new Exception("FtpHelper Delete Error --> " + ex.Message + "  文件名:" + folderName);
     }
 }
Exemplo n.º 12
0
        private void Rename(string currentFilename, string newFilename)//重命名方法
        {
            FtpWebRequest reqFTP;

            try
            {
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.parent.ftpServerIP + "/" + currentFilename));
                reqFTP.Method      = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo    = newFilename;
                reqFTP.UseBinary   = true;
                reqFTP.UsePassive  = false;
                reqFTP.Credentials = new NetworkCredential(this.parent.ftpUserID, this.parent.ftpPassword);
                FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
                MessageBox.Show("重命名成功!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// get the folder or file list from a well-form ftp url
        /// </summary>
        /// <param name="ftpUrl">a well-form ftp url including all the directories. e.g. http://myip/mydir/mysubdir </param>
        /// <returns>the list under the given ftpUrl</returns>
        private List <string> GetDataList(string ftpUrl)
        {
            List <string> dataList = new List <string>();

            try
            {
                FtpWebRequest  ftpRequest     = GetFtpRequest(ftpUrl, WebRequestMethods.Ftp.ListDirectory);
                FtpWebResponse response       = (FtpWebResponse)ftpRequest.GetResponse();
                Stream         responseStream = response.GetResponseStream();
                StreamReader   reader         = new StreamReader(responseStream);
                while (!reader.EndOfStream)
                {
                    dataList.Add(reader.ReadLine());
                }
                reader.Close();
                responseStream.Dispose();
            }
            catch
            {
                throw;
            }

            return(dataList);
        }
Exemplo n.º 14
0
        public Stream GetFile(string file)
        {
            try
            {
                Logger.LogInformation("FtpWebRequest: Attempting to receive file: " + file);
                string uri = CreateUrl(file);

                Uri ftpServerUri = new Uri(uri);

                if (ftpServerUri.Scheme != Uri.UriSchemeFtp)
                {
                    return(null);
                }

                var reqFtp = CreateRequest(file);
                reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();


                Stream responseStream = new MemoryStream();

                response.GetResponseStream().CopyTo(responseStream);

                responseStream.Seek(0, SeekOrigin.Begin);

                response.Close();

                Logger.LogInformation("FtpWebRequest: File has been received successfully.");
                return(responseStream);
            }
            catch (Exception ex)
            {
                Logger.LogError("FtpWebRequest: Get File failed Exception: " + ex.Message);
                return(null);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 获取目录的文件
        /// </summary>
        public List <FileStruct> GetFiles(string dirName)
        {
            var fileList = new List <FileStruct>();

            response = Open(new Uri(ftpUri + dirName), WebRequestMethods.Ftp.ListDirectory);
            if (response == null)
            {
                return(fileList);
            }

            try
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(stream, Encoding.Default))
                    {
                        string line = null;
                        while ((line = sr.ReadLine()) != null)
                        {
                            var model = new FileStruct()
                            {
                                Name = line,
                                Path = dirName + "/" + line
                            };
                            fileList.Add(model);
                        }
                    }
                }
                return(fileList);
            }
            catch (Exception e)
            {
                LoggerHelper.Error("获取目录【" + dirName + "】的文件失败", e);
                return(fileList);
            }
        }
Exemplo n.º 16
0
        public static string CreateDirectory(string ftpPath)
        {
            string success = "";

            try
            {
                FtpWebRequest requestDir = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
                requestDir.Credentials = networkCredentials;
                requestDir.Method      = WebRequestMethods.Ftp.MakeDirectory;
                requestDir.UsePassive  = true;
                requestDir.UseBinary   = true;
                requestDir.KeepAlive   = false;
                FtpWebResponse response  = (FtpWebResponse)requestDir.GetResponse();
                Stream         ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
                success = "ok";
            }
            catch (Exception ex)
            {
                success = Helpers.ErrorDetails(ex);
            }
            return(success);
        }
Exemplo n.º 17
0
        public static string Download()
        {
            Console.WriteLine(Environment.GetEnvironmentVariable("FTP_USER"));
            // Get the object used to communicate with the server.
            string        encoded = HttpUtility.UrlEncode("test.txt");
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://13.251.156.227/" + encoded);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential(Environment.GetEnvironmentVariable("FTP_USER"), Environment.GetEnvironmentVariable("FTP_PW"));

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

            Stream       responseStream = response.GetResponseStream();
            StreamReader reader         = new StreamReader(responseStream);
            string       content        = reader.ReadToEnd();

            Console.WriteLine($"Download Complete, status {response.StatusDescription}");

            reader.Close();
            response.Close();
            return(content);
        }
Exemplo n.º 18
0
        //public bool FtpDirectoryExists(string directoryPath)
        //{
        //    bool IsExists = false;
        //    FtpWebResponse response = null;
        //    try
        //    {
        //        FtpWebRequest reqFTP = GetFtpWebRequest(directoryPath);
        //        reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
        //        response = (FtpWebResponse)reqFTP.GetResponse();
        //        IsExists = true;
        //    }
        //    catch (Exception)
        //    {
        //        throw;
        //    }
        //    finally
        //    {
        //        if (response != null)
        //            response.Close();
        //    }
        //    return IsExists;
        //}

        public void FTPMakeDir(string pathToCreate)
        {
            string[] subDirs = pathToCreate.Split('/');
            string   cur_dir = "";

            foreach (string subDir in subDirs)
            {
                cur_dir = cur_dir + "/" + subDir;
                //if (FtpDirectoryExists(cur_dir))
                //    continue;

                FtpWebResponse response  = null;
                Stream         ftpStream = null;
                try
                {
                    FtpWebRequest reqFTP = GetFtpWebRequest(cur_dir);
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                    response      = (FtpWebResponse)reqFTP.GetResponse();
                    ftpStream     = response.GetResponseStream();
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (ftpStream != null)
                    {
                        ftpStream.Close();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
        }
Exemplo n.º 19
0
 public void RemoveFile(string fileName)
 {
     try
     {
         FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(new Uri(this.GetUri(fileName)));
         ftpWebRequest.Credentials = new NetworkCredential(this._strUser, this._strPass);
         ftpWebRequest.KeepAlive   = false;
         ftpWebRequest.Method      = "DELE";
         string         text           = string.Empty;
         FtpWebResponse ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
         long           contentLength  = ftpWebResponse.ContentLength;
         Stream         responseStream = ftpWebResponse.GetResponseStream();
         StreamReader   streamReader   = new StreamReader(responseStream);
         text = streamReader.ReadToEnd();
         streamReader.Close();
         responseStream.Close();
         ftpWebResponse.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "FTP 2.0 Delete");
         throw ex;
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// 获取指定文件大小
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long          fileSize = 0;

            try
            {
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
                reqFTP.Method      = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(fileSize);
        }
Exemplo n.º 21
0
 /// <summary>
 /// 删除文件
 /// </summary>
 public void Delete(string fileName)
 {
     try
     {
         FtpWebRequest reqFTP;
         reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
         reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
         reqFTP.Method      = WebRequestMethods.Ftp.DeleteFile;
         reqFTP.KeepAlive   = false;
         string         result     = String.Empty;
         FtpWebResponse response   = (FtpWebResponse)reqFTP.GetResponse();
         long           size       = response.ContentLength;
         Stream         datastream = response.GetResponseStream();
         StreamReader   sr         = new StreamReader(datastream);
         result = sr.ReadToEnd();
         sr.Close();
         datastream.Close();
         response.Close();
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 22
0
        public void DownloadFile(string ftpURL, string UserName, string Password, string ftpDirectory, string FileName, string LocalDirectory)
        {
            if (!File.Exists(LocalDirectory + "/" + FileName))
            {
                try
                {
                    // implement a file transfer protocol client
                    FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + ftpDirectory + "/" + FileName);
                    requestFileDownload.Credentials = new NetworkCredential(UserName, Password);                            // pass the credentials
                    requestFileDownload.Method      = WebRequestMethods.Ftp.DownloadFile;                                   // download file method
                    FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();                // response method to the Download
                    Stream         responseStream       = responseFileDownload.GetResponseStream();                         // contains the response data
                    FileStream     writeStream          = new FileStream(LocalDirectory + "/" + FileName, FileMode.Create); // writes the file to the directory
                    int            Length    = 2048;
                    Byte[]         buffer    = new Byte[Length];
                    int            bytesRead = responseStream.Read(buffer, 0, Length);
                    statusListBox.Items.Add("•" + responseFileDownload.StatusDescription);
                    while (bytesRead > 0)  // while there are bytes read
                    {
                        writeStream.Write(buffer, 0, bytesRead);
                        bytesRead = responseStream.Read(buffer, 0, Length);
                    }
                    statusListBox.Items.Add("•" + responseFileDownload.StatusDescription);
                    responseStream.Close();     // close the response stream
                    writeStream.Close();        // close the write stream
                    requestFileDownload = null; // set to null, to allow a re-call of the function

                    successStatusLabel.Text = "Download Completed";
                }
                catch (Exception ex)
                {
                    statusListBox.Items.Add("•" + ex.Message);
                    successStatusLabel.Text = ex.Message;
                }
            }
        }
Exemplo n.º 23
0
        /* Get the Date/Time a File was Created */
        public string getFileCreatedDateTime(string fileName)
        {
            /* Create an FTP Request */
            m_ftpRequest = (FtpWebRequest)FtpWebRequest.Create(m_host + "/" + fileName);
            /* Log in to the FTP Server with the User Name and Password Provided */
            m_ftpRequest.Credentials = new NetworkCredential(m_user, m_pass);
            /* When in doubt, use these options */
            m_ftpRequest.UseBinary  = true;
            m_ftpRequest.UsePassive = true;
            m_ftpRequest.KeepAlive  = true;
            /* Specify the Type of FTP Request */
            m_ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
            /* Establish Return Communication with the FTP Server */
            m_ftpResponse = (FtpWebResponse)m_ftpRequest.GetResponse();
            /* Establish Return Communication with the FTP Server */
            m_ftpStream = m_ftpResponse.GetResponseStream();
            /* Get the FTP Server's Response Stream */
            StreamReader ftpReader = new StreamReader(m_ftpStream);
            /* Store the Raw Response */
            string fileInfo = null;

            /* Read the Full Response Stream */
            try
            {
                fileInfo = ftpReader.ReadToEnd();
            }
            finally
            {
                /* Resource Cleanup */
                ftpReader.Close();
                m_ftpStream.Close();
                m_ftpResponse.Close();
                /* Return File Created Date Time */
            }
            return(fileInfo);
        }
Exemplo n.º 24
0
    // FTP 列出檔案名稱
    protected ArrayList List(string listUrl, string UserName, string Password)
    {
        StreamReader reader       = null;
        ArrayList    FileNameList = new ArrayList();


        FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(listUrl);

        listRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
        listRequest.Credentials = new NetworkCredential(UserName, Password);

        FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse();

        reader = new StreamReader(listResponse.GetResponseStream());

        /*
         *  while (reader.Peek() >= 0)
         *  {
         *      FileNameList.Add(reader.ReadLine());
         *  }
         */

        string line = reader.ReadLine();

        while (line != null)
        {
            FileNameList.Add(line);
            line = reader.ReadLine();
        }

        reader.Close();
        listResponse.Close();

        return(FileNameList);
        //回傳目前清單
    }
Exemplo n.º 25
0
        /// <summary>
        /// FTP 서버에 있는 텍스트 파일의 내용을 리턴함.
        /// </summary>
        /// <param name="RemoteFolder">서버의 폴더 위치</param>
        /// <param name="RemoteFile">서버의 텍스트 파일 이름</param>
        /// <returns>텍스트 파일의 내용</returns>
        public string GetText(string RemoteFolder, string RemoteFile)
        {
            Uri RemoteUri = GetRemoteUri(RemoteFolder, RemoteFile);

            FtpWebRequest FtpReq = (FtpWebRequest)WebRequest.Create(RemoteUri);

            if (!string.IsNullOrEmpty(this._Info.UserId))
            {
                FtpReq.Credentials = new NetworkCredential(this._Info.UserId, this._Info.Password);
            }
            FtpReq.UsePassive = this._Info.UsePassive;

            FtpReq.Method = WebRequestMethods.Ftp.DownloadFile;

            FtpWebResponse FtpResp = (FtpWebResponse)FtpReq.GetResponse();

            StreamReader sr = new StreamReader(FtpResp.GetResponseStream(), System.Text.Encoding.UTF8);
            string       s  = sr.ReadToEnd();

            sr.Close();
            FtpResp.Close();

            return(s);
        }
Exemplo n.º 26
0
        public List <string> DirectoryListing(string host, string userName, string password)
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(@"ftp://" + host);

            request.Method = WebRequestMethods.Ftp.ListDirectory;

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

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

            Stream        responseStream = response.GetResponseStream();
            StreamReader  reader         = new StreamReader(responseStream);
            List <string> files          = new List <string>();

            while (!reader.EndOfStream)
            {
                files.Add(reader.ReadLine());
            }
            reader.Close();
            response.Close();
            return(files);
        }
Exemplo n.º 27
0
        /// <summary>

        /// 下载

        /// </summary>

        /// <param name="filePath"></param>

        /// <param name="fileName"></param>

        public void Download(string filePath, string fileName)
        {
            FtpWebRequest reqFTP;

            try
            {
                FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

                //reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + 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)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Obtains a response stream as a string
        /// </summary>
        /// <param name="ftp">current FTP request</param>
        /// <returns>String containing response</returns>
        /// <remarks>FTP servers typically return strings with CR and
        /// not CRLF. Use respons.Replace(vbCR, vbCRLF) to convert
        /// to an MSDOS string</remarks>
        private string GetStringResponse(FtpWebRequest ftp)
        {
            //Get the result, streaming to a string
            string result = "";

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                long size = response.ContentLength;
                using (Stream datastream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(datastream))
                    {
                        result = sr.ReadToEnd();
                        sr.Close();
                    }

                    datastream.Close();
                }

                response.Close();
            }

            return(result);
        }
Exemplo n.º 29
0
        /// <summary>
        /// 获取指定文件大小
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long          fileSize = 0;

            try
            {
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
                reqFTP.Method      = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream = response.GetResponseStream();
                fileSize = response.ContentLength;

                ftpStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + ex.Message);
            }
            return(fileSize);
        }
Exemplo n.º 30
0
        public List <string> DirectoryListing(string Path, string ServerAdress, string Login, string Password)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ServerAdress + "/" + Path);

            request.Credentials = new NetworkCredential(Login, Password);

            request.Method = WebRequestMethods.Ftp.ListDirectory;

            FtpWebResponse response       = (FtpWebResponse)request.GetResponse();
            Stream         responseStream = response.GetResponseStream();
            StreamReader   reader         = new StreamReader(responseStream);

            List <string> result = new List <string>();

            while (!reader.EndOfStream)
            {
                result.Add(reader.ReadLine());
            }

            reader.Close();
            response.Close();

            return(result);
        }
Exemplo n.º 31
0
        private void _download()
        {
            try
            {
                String         idd      = _id;
                FtpWebResponse response = get_reader(realPath, USESSL, WebRequestMethods.Ftp.DownloadFile);
                Stream         reader   = response.GetResponseStream();
                FileStream     output   = new FileStream(targetPath, FileMode.OpenOrCreate);
                byte[]         buffer   = new byte[2048];
                int            leng     = 0;
                double         current  = 0;
                //开始计时*************************************************

                while ((leng = reader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    current += leng;
                    //*****************************************************
                    output.Write(buffer, 0, leng);
                    double real = (current / total) * 100;
                    int    prog = (int)Math.Ceiling(real);
                    list[idd][0] = current;
                    //不加这句,label将会来不及显示
                    System.Windows.Forms.Application.DoEvents();
                }
                output.Close();
                output.Dispose();
                reader.Close();
                reader.Dispose();
                response.Close();
                response.Dispose();
                totalnum--;
            }catch (Exception e)
            {
                MessageBox.Show("下载出错。" + e.Message);
            }
        }
Exemplo n.º 32
0
        public string[] GetFileList(string directoryname)
        {
            StringBuilder stringBuilder = new StringBuilder();
            string        fullName      = this.getFullName(directoryname, true);

            this.Connect(fullName);
            this.FtpWr.Method    = "NLST";
            this.FtpWr.UseBinary = true;
            FtpWebResponse ftpWebResponse = (FtpWebResponse)this.FtpWr.GetResponse();
            StreamReader   streamReader   = new StreamReader(ftpWebResponse.GetResponseStream(), Encoding.Default);

            for (string text = streamReader.ReadLine(); text != null; text = streamReader.ReadLine())
            {
                stringBuilder.Append(text);
                stringBuilder.Append("\n");
            }
            stringBuilder.Remove(stringBuilder.ToString().LastIndexOf('\n'), 1);
            streamReader.Close();
            ftpWebResponse.Close();
            return(stringBuilder.ToString().Split(new char[]
            {
                '\n'
            }));
        }
Exemplo n.º 33
0
        //public void Connect()
        //{

        //}

        public void Download(string remotePath, string localPath)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host + ":" + port + "/" + remotePath);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

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

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

            Stream       responseStream = response.GetResponseStream();
            StreamReader reader         = new StreamReader(responseStream);

            using (StreamWriter writer = new StreamWriter(localPath))
            {
                writer.Write(reader);
            }

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

            reader.Close();
            response.Close();
        }
Exemplo n.º 34
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 "";
	}
Exemplo n.º 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;
    }