The FtpWebRequest class implements a basic FTP client interface.

상속: WebRequest
예제 #1
1
        /// <summary>
        /// 连接FTP的方法
        /// </summary>
        /// <param name="ftpuri">ftp服务器地址,端口</param>
        /// <param name="ftpUserID">用户名</param>
        /// <param name="ftpPassword">密码</param>
        public DownloadFtp(string ftpuri, string ftpUserID, string ftpPassword)
        {
            // 根据uri创建FtpWebRequest对象
              ft = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpuri));
              // ftp用户名和密码
              ft.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
              ft.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
             fr = (FtpWebResponse)ft.GetResponse();
              stream = fr.GetResponseStream();
              ////二进制文件读入
              //if (!fr.ContentType.ToLower().StartsWith("text/"))
              //{
              //    SaveBinaryFile(fr);
              //}
              ////文本文件
              //else
              //{
              string buffer = "", line;
              StreamReader reader = new StreamReader(stream);
              while ((line = reader.ReadLine()) != null)
              {
                  buffer += line + "\r\n";
              }

              //装入整个文件之后,接着就要把它保存为文本文件。
              SaveTextFile(buffer);
              //}
        }
예제 #2
0
        /// <summary>
        /// 判断ftp服务器上该目录是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="ftpHostIP"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private static bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
        {
            bool flag = true;

            try
            {
                string uri = "ftp://" + ftpHostIP + "/" + dirName;
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = ftp.GetResponse();

                var    reader = new StreamReader(response.GetResponseStream());
                string line   = reader.ReadLine();

                if (string.IsNullOrEmpty(line))
                {
                    flag = false;
                }
                response.Close();
            }
            catch (Exception ex)
            {
                flag = false;
                LogHelper.WriteLog("ftp获取目录异常," + ex.Message);
            }

            return(flag);
        }
        public static bool WriteFileToFTP(string HostName, int Port, string UserName, string Password, string targetPath, byte[] fileBytes)
        {
            bool fileCopied = false;

            try
            {
                using (FtpClient ftp = new FtpClient(HostName, Port, UserName, Password))
                {
                    ftp.Connect();
                    System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create("ftp://" + HostName + targetPath);
                    clsRequest.Credentials = new System.Net.NetworkCredential(UserName, Password);
                    clsRequest.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                    System.IO.Stream clsStream = clsRequest.GetRequestStream();
                    clsStream.Write(fileBytes, 0, fileBytes.Length);
                    clsStream.Close();
                    clsStream.Dispose();
                    fileCopied = true;
                }
            }
            catch (Exception)
            {
                return(fileCopied);
            }
            return(fileCopied);
        }
예제 #4
0
        public bool copyToServer(string remote, string local, string logPath)
        {
            bool success = false;
//            try
//            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(host + remote);
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                ftpRequest.Credentials = netCreds;

                byte[] b = File.ReadAllBytes(local);

                ftpRequest.ContentLength = b.Length;
                using (Stream s = ftpRequest.GetRequestStream())
                {
                    s.Write(b, 0, b.Length);
                }

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                // check was successful
                if (ftpResponse.StatusCode == FtpStatusCode.ClosingData)
                {
                    success = true;
                    logResult(remote, host, user, logPath);
                }
                ftpResponse.Close();
                
/*            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }*/
            return success;
        }
예제 #5
0
		internal FtpWebResponse (FtpWebRequest request, Uri uri, string method, bool keepAlive)
		{
			this.request = request;
			this.uri = uri;
			this.method = method;
			//this.keepAlive = keepAlive;
		}
예제 #6
0
        /// <summary>
        /// 上传文件
        /// </summary> /
        // <param name="fileinfo">需要上传的文件</param>
        /// <param name="targetDir">目标路径</param>
        /// <param name="hostname">ftp地址</param> /
        // <param name="username">ftp用户名</param> /
        // <param name="password">ftp密码</param>
        public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
        { //1. check target
            string target;

            if (targetDir.Trim() == "")
            {
                return;
            }
            target = Guid.NewGuid().ToString();
            //使用临时文件名
            string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;

            ///WebClient webcl = new WebClient();
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
            //设置FTP命令 设置所要执行的FTP命令,
            //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //指定文件传输的数据类型
            ftp.UseBinary     = true;
            ftp.UsePassive    = true; //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2KB
            const int BufferSize = 2048;

            byte[] content = new byte[BufferSize - 1 + 1];
            int    dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件

            using (FileStream fs = fileinfo.OpenRead())
            {
                try
                { //把上传的文件写入流
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        { //每次读文件流的2KB
                            dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead);
                        }while (!(dataRead < BufferSize)); rs.Close();
                    }
                }
                catch (Exception ex) { }
                finally { fs.Close(); }
            }
            ftp          = null;                                    //设置FTP命令
            ftp          = GetRequest(URI, username, password);
            ftp.Method   = System.Net.WebRequestMethods.Ftp.Rename; //改名
            ftp.RenameTo = fileinfo.Name; try { ftp.GetResponse(); }
            catch (Exception ex)
            {
                ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
                ftp.GetResponse(); throw ex;
            }
            finally
            {
                //fileinfo.Delete(); } // 可以记录一个日志 "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
                ftp = null;
                #region
                /***** *FtpWebResponse * ****/ //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
                #endregion
            }
        }
예제 #7
0
        /// <summary>
        /// FTP 서버 내의 파일 이름을 변경합니다.
        /// </summary>
        /// <param name="sourceFilename">대상 파일의 경로를 입력합니다.</param>
        /// <param name="newName">대상 파일의 경로와 함께 새로운 이름을 입력합니다.</param>
        /// <returns>성공 시 true를, 실패시 false를 리턴합니다.</returns>
        public static bool FTPRename(string sourceFilename, string newName)
        {
            string source = GetFullPath(sourceFilename);

            if (!FTPFileExists(source))
            {
                throw (new FileNotFoundException("File " + source + " not found"));
            }

            string target = GetFullPath(newName);

            if (target == source)
            {
                throw (new ApplicationException("Source and target are the same"));
            }
            else if (FTPFileExists(target))
            {
                throw (new ApplicationException("Target file " + target + " already exists"));
            }

            string URI = Hostname + source;

            System.Net.FtpWebRequest ftp = GetRequest(URI);
            ftp.Method   = System.Net.WebRequestMethods.Ftp.Rename;
            ftp.RenameTo = target;

            try {
                string str = GetStringResponse(ftp);
            }
            catch (Exception) {
                return(false);
            }
            return(true);
        }
예제 #8
0
        public static bool ExistFile(string _path, string _user, string _pass)
        {
            bool res = false;

            try
            {
                System.Net.FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_path);
                ftpRequest.Method      = WebRequestMethods.Ftp.GetDateTimestamp;
                ftpRequest.Credentials = new NetworkCredential(_user, _pass);
                ftpRequest.UseBinary   = true;
                ftpRequest.UsePassive  = true;
                ftpRequest.KeepAlive   = false;
                ftpRequest.EnableSsl   = Core.Global.GetConfig().ConfigFTPSSL;
                System.Net.FtpWebResponse response;
                try
                {
                    response = (FtpWebResponse)ftpRequest.GetResponse();
                    res      = true;
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                catch (Exception)
                {
                    res = false;
                }
            }
            catch (Exception ex)
            {
                Core.Error.SendMailError(ex.ToString());
            }
            return(res);
        }
예제 #9
0
        public bool FtpCreateDirectory(string dirpath)
        {
            string URI = this.Hostname + AdjustDir(dirpath) + "/";

            System.Net.FtpWebRequest ftp = GetRequest(URI);
            ftp.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory;

            try
            {
                ftp.UseBinary = true;

                ftp.Credentials = new NetworkCredential(Global.ConfigInfo.FtpUser, Global.ConfigInfo.FtpPw);
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();

                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
예제 #10
0
 /* Create a New Directory on the FTP Server */
 public bool createDirectory(string newDirectory)
 {
     bool result = true;
      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)
      {
     StockLog.Write(ex.ToString());
     result = false;
      }
      return result;
 }
예제 #11
0
파일: ClasseFtp.cs 프로젝트: prasist/wb20
        public bool VerificaSeExiste(string destinfilepath, string ftphost, string ftpfilepath, string user, string pass)
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftphost + "//" + ftpfilepath);

            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            try {
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();                
                ftpRequest = null;
                return true;
            }
            catch (Exception exc)
            {
                this.sErro = exc.Message;                
                return false;
            }
             
        }
예제 #12
0
        private static void setProxyInfo(SetupConf setVariables, FtpWebRequest request)
        {
            try
            {
                string strProxyServer = setVariables.objProxyVariables.proxyServer.ToString();
                string strProxyPort = setVariables.objProxyVariables.proxyPort.ToString();
                string strProxyUsername = setVariables.objProxyVariables.proxyUsername.ToString();
                string strProxyPassword = setVariables.objProxyVariables.proxyPassword.ToString();

                IWebProxy proxy = request.Proxy;
                if (proxy != null)
                {
                    Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
                }

                WebProxy myProxy = new WebProxy();
                Uri newUri = new Uri(Uri.UriSchemeHttp + "://" + strProxyServer + ":" + strProxyPort);
                // Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
                myProxy.Address = newUri;
                // Create a NetworkCredential object and associate it with the
                // Proxy property of request object.
                myProxy.Credentials = new NetworkCredential(strProxyUsername, strProxyPassword);
                request.Proxy = myProxy;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
                Console.ReadLine();
                System.Environment.Exit(-1);
            }
        }
예제 #13
0
 private static void init(string method)
 {
     request = (FtpWebRequest) WebRequest.Create("ftp://" + server + path + file_name);
     request.Method = method;
     
     request.Credentials = new NetworkCredential("anonymous", "password");
 }
예제 #14
0
        /// <summary>
        /// 判断ftp服务器上该目录是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="ftpHostIP"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private static bool ftpIsExistsPath(string dirName, string ftpHostIP, string username, string password)
        {
            bool flag = true;

            try
            {
                string uri = "ftp://" + ftpHostIP + "/" + dirName;
                if (!uri.EndsWith("/"))
                {
                    uri = uri + "/";
                }
                System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
                ftp.Credentials = new NetworkCredential(username, password);
                ftp.Method      = WebRequestMethods.Ftp.ListDirectory;
                ftp.UseBinary   = true;
                ftp.UsePassive  = true;

                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
            }
            catch (Exception ex)
            {
                flag = false;
                LogWriter.Write("判断ftp服务器上该目录是否存在", ex.Message, "FileUrl_EXT");
            }
            return(flag);
        }
예제 #15
0
        /// <summary>
        /// Upload localName to the FTP site.
        /// </summary>
        /// <param name="localName">The full path to the file to upload on the local device.</param>
        /// <param name="destBaseVal">The base file name.</param>
        /// <param name="ftpPathVal">FTP path</param>
        /// <param name="ftpUserNameVal">FTP user</param>
        /// <param name="ftpPasswordVal">FTP password</param>
        public void FtpUpload(string localName, string destBaseVal, string ftpPathVal, string ftpUserNameVal, string ftpPasswordVal)
        {
            try
            {
                System.Net.FtpWebRequest request = null;

                request                     = WebRequest.Create(new Uri(ftpPathVal + destBaseVal)) as FtpWebRequest;
                request.Method              = WebRequestMethods.Ftp.UploadFile;
                request.UseBinary           = false;
                request.UsePassive          = false;
                request.KeepAlive           = false;
                request.Credentials         = new NetworkCredential(ftpUserNameVal, ftpPasswordVal);
                request.ConnectionGroupName = "group";

                using (System.IO.FileStream fs = System.IO.File.OpenRead(localName))
                {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    fs.Close();
                    System.IO.Stream requestStream = request.GetRequestStream();
                    requestStream.Write(buffer, 0, buffer.Length);
                    requestStream.Flush();
                    requestStream.Close();
                }
                // uploaded successfully
            }
            catch (Exception ex)
            {
                throw new Exception("FtpUpload: " + ftpPathVal + destBaseVal + " upload failed: " + ex.Message);
            }
        }
예제 #16
0
        /// <summary>
        /// 搜索远程文件
        /// </summary>
        /// <param name="targetDir"></param>
        /// <param name="hostname"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="SearchPattern"></param>
        /// <returns></returns>
        public static List <string> ListDirectory(string targetDir, FTP ftpSrv, string SearchPattern)
        {
            List <string> result = new List <string>();

            try
            {
                string URI = "FTP://" + ftpSrv.hostname + "/" + targetDir + "/" + SearchPattern;

                System.Net.FtpWebRequest ftp = GetRequest(URI, ftpSrv.username, ftpSrv.password);
                ftp.Method     = System.Net.WebRequestMethods.Ftp.ListDirectory;
                ftp.UsePassive = true;
                ftp.UseBinary  = true;


                string str = GetStringResponse(ftp);
                str = str.Replace("\r\n", "\r").TrimEnd('\r');
                str = str.Replace("\n", "\r");
                if (str != string.Empty)
                {
                    result.AddRange(str.Split('\r'));
                }

                return(result);
            }
            catch { }
            return(null);
        }
예제 #17
0
        /// <summary>
        /// Return a detailed directory listing, and also download datetime stamps if specified
        /// </summary>
        /// <param name="directory">Directory to list, e.g. /pub/etc</param>
        /// <param name="doDateTimeStamp">Boolean: set to True to download the datetime stamp for files</param>
        /// <returns>An FTPDirectory object</returns>
        public FTPdirectory ListDirectoryDetail(string directory, bool doDateTimeStamp)
        {
            String URI = GetDirectory(directory);

            System.Net.FtpWebRequest ftp = GetRequest(URI);
            // Set request to do simple list
            ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;

            string str = GetStringResponse(ftp);

            // replace CRLF to CR, remove last instance
            str = str.Replace("\r\n", "\r").TrimEnd('\r');
            // split the string into a list
            FTPdirectory dir = new FTPdirectory(str, _lastDirectory);

            // download timestamps if requested
            if (doDateTimeStamp)
            {
                foreach (FTPfileInfo fi in dir)
                {
                    fi.FileDateTime = this.GetDateTimestamp(fi);
                }
            }

            return(dir);
        }
예제 #18
0
파일: FtpClient.cs 프로젝트: techcap/CSharp
        /// <summary>
        /// Determine size of remote file
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        /// <remarks>Throws an exception if file does not exist</remarks>
        public long GetFileSize(string filename)
        {
            string path;

            if (filename.Contains("/"))
            {
                path = AdjustDir(filename);
            }
            else
            {
                path = this.CurrentDirectory + filename;
            }
            string URI = this.Hostname + path;

            //string URI = "ftp://*****:*****@www.js-system.co.kr/PDS/KMNC/Ver_Info.xml";

            System.Net.FtpWebRequest ftp = GetRequest(URI);
            //Try to get info on file/dir?
            ftp.Proxy = null;
            //ftp.Method = System.Net.WebRequestMethods.Ftp.GetFileSize;
            ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
            string tmp = this.GetStringResponse(ftp);

            return(GetSize(ftp));
        }
예제 #19
0
        /// <summary>
        /// 디렉토리 전체를 삭제
        /// </summary>
        /// <param name="dirpath">파일이 존재하는 디렉토리 (DONGSHIN 이하 전부 기입)</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public bool DeleteDirectory(string dirpath)
        {
            try
            {
                //실제로 디렉토리가 존재하면 삭제 실행
                if (IsExtistDirectory(dirpath))
                {
                    //디렉토리 안에 파일이 존재하면 삭제 후 디렉토리 삭제
                    List <string> fileNameList = new List <string>();
                    fileNameList = GetFileNameList(dirpath);
                    if (fileNameList.Count > 0)
                    {
                        for (int i = 0; i < fileNameList.Count; i++)
                        {
                            DeleteFile(string.Format("{0}/{1}", dirpath, fileNameList[i]));
                        }
                    }

                    string URI = this.Host + AdjustDir(dirpath);
                    System.Net.FtpWebRequest ftp = GetRequest(URI);
                    ftp.Method = System.Net.WebRequestMethods.Ftp.RemoveDirectory;

                    //get response but ignore it
                    string str = GetStringResponse(ftp);
                    //Give Message of Command
                    NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Remove Directory", "RMD");
                    //OnNewMessageReceived(this, e);
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
예제 #20
0
        public string FTP_CreateDirectory(string cname) // 채널 생성시 FTP 디렉토리를 채널명으로 생성한다.
        {
            try
            {
                System.Net.FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://192.168.0.8:8000/home/" + cname);
                request.Credentials = new NetworkCredential(FTPid, FTPpw);
                request.UsePassive  = true;
                request.UseBinary   = true;
                request.KeepAlive   = false;
                request.Method      = WebRequestMethods.Ftp.MakeDirectory;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("FTP Directory Created by channel name : " + response.StatusDescription);

                response.Close();

                return("성공");
            }
            catch (Exception)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("[FTP Directory Create Failed]");

                return("실패");
            }
        }
예제 #21
0
파일: Program.cs 프로젝트: Ruandv/Training
        private static Boolean GetVersion(FtpWebRequest request)
        {
            Console.WriteLine("Checking Local Version...");
            var f = new StreamReader(@".\Connections\version.json");
            string data = f.ReadToEnd();
            versionsInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionInfo>(data);

            credentials = new NetworkCredential(versionsInfo.ServerUserName,versionsInfo.ServerPassword);
            Console.WriteLine("Connecting to server...");
            request = (FtpWebRequest)WebRequest.Create(versionsInfo.ServerUrl + "Version.json");
            request.Credentials = credentials;
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            Console.WriteLine("Downloading...");
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            serverVersion = Newtonsoft.Json.JsonConvert.DeserializeObject<VersionInfo>(reader.ReadToEnd());
            Console.WriteLine("Close Server Connections...");
            reader.Close();
            response.Close();

            Console.WriteLine("Server Version : " + serverVersion.Version);
            Console.WriteLine("Local Version : " + versionsInfo.Version);
            f.Close();

            return versionsInfo.Version < serverVersion.Version;
            //Console.WriteLine(versionsInfo.Version);
            //f.ToString();
        }
예제 #22
0
        /// <summary>
        /// 파일명 리스트 구하기
        /// </summary>
        /// <param name="dirPath">서버 디렉토리</param>
        /// <returns>파일명 리스트</returns>
        public List <string> GetFileNameList(string dirpath)
        {
            List <string> fileNameList = new List <string>();

            string URI = string.Format("{0}/{1}", this.Host, dirpath);

            System.Net.FtpWebRequest ftp = GetRequest(URI);
            ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;

            //WebResponse webResponse = null;
            try
            {
                string   str = GetStringResponse(ftp);
                string[] filesInDirectory = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < filesInDirectory.Length; i++)
                {
                    string filename = filesInDirectory[i].Substring(filesInDirectory[i].LastIndexOf("/") + 1);
                    if (filename.Length >= 4)
                    {
                        fileNameList.Add(filename);
                    }
                }
            }
            catch (Exception ex) { throw ex; }

            return(fileNameList);
        }
예제 #23
0
 private static System.Net.FtpWebRequest GetRequest(string URL, string UserName, string Password)
 {
     System.Net.FtpWebRequest result = System.Net.FtpWebRequest.Create(URL) as System.Net.FtpWebRequest;
     result.Credentials = new System.Net.NetworkCredential(UserName, Password);
     result.KeepAlive   = false;
     return(result);
 }
예제 #24
0
파일: FtpUpload.cs 프로젝트: yarivat/Admin
        /// <summary>
        /// Check FTP connection to the server
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool CheckConnection(string host, string port, string username, string password)
        {
            try
            {
                if (!string.IsNullOrEmpty(port))
                {
                    host += ":" + port;
                }
                System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.HttpWebRequest.Create("ftp://" + host);

                myFTP.Credentials = new System.Net.NetworkCredential(username, password);

                myFTP.UsePassive = true;
                myFTP.UseBinary  = true;
                myFTP.KeepAlive  = false;

                myFTP.Method = System.Net.WebRequestMethods.Ftp.PrintWorkingDirectory;

                myFTP.GetResponse();

                return(true);
            }
            catch (Exception ex)
            {
                throw new DuradosException("FTP Connection failed, Error: " + ex.Message);
                //return false;
            }
        }
예제 #25
0
        /// <summary>
        /// 判断ftp服务器上该目录是否存在
        /// </summary>
        /// <param name="dirName"></param>
        /// <param name="ftpHostIP"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool ftpIsExistsFile(out string msg, string dirName, string ftpHostIP, string username, string password)
        {
            bool flag = false;

            msg = string.Empty;
            string uri = "ftp://" + ftpHostIP + "/" + dirName;

            //string[] value = GetFileList(pFtpServerIP, pFtpUserID, pFtpPW);
            System.Net.FtpWebRequest ftp = null;
            try
            {
                ftp = GetRequest(uri, username, password);
                //ftp.Method = WebRequestMethods.Ftp.ListDirectory;
                ftp.Method    = WebRequestMethods.Ftp.ListDirectoryDetails;
                ftp.KeepAlive = false;
                //ftp.GetResponse();
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                StreamReader   reader   = new StreamReader(response.GetResponseStream());
                string         line     = reader.ReadLine();
                //FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
                if (line != null)
                {
                    flag = true;
                }
            }
            catch (Exception x)
            {
                msg  = x.Message;
                flag = false;
            }
            return(flag);
        }
예제 #26
0
        public string ftpFile(string fileName)
        {
            try
            {
                System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(fileName);
                tmpReq.Credentials = new System.Net.NetworkCredential("", "");

                //GET THE FTP RESPONSE
                using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
                {
                    //GET THE STREAM TO READ THE RESPONSE FROM
                    using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
                    {
                        //CREATE A TXT READER (COULD BE BINARY OR ANY OTHER TYPE YOU NEED)
                        using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream))
                        {
                            //STORE THE FILE CONTENTS INTO A STRING
                            return(tmpReader.ReadToEnd());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error Reading FTP File", ex);
            }
        }
예제 #27
0
        public void DownloadFile(string remoteFile, string localFile)
        {
            // Создаем FTP Request
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, remoteFile));
            // Инициализируем сетевые учетные данные
            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            // Задаем команду, которая будет отправлена на FTP-сервер
            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpRequest.Timeout = TIMEOUT;
            // Ответ FTP-сервера
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            // Возвращаем поток данных
            ftpStream = ftpResponse.GetResponseStream();
            // Создаем локальный файл
            FileStream localFileStream = new FileStream(localFile, FileMode.Create);
            // Пишем в файл
            ftpStream.CopyTo(localFileStream);

            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
    public string FTPFileReader(String FileName, string username, string password)
    {
        string Res = "";

        System.IO.StreamReader   Q1     = null;
        System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(FileName);
        tmpReq.Credentials = new NetworkCredential(username, password);
        tmpReq.UsePassive  = true;
        tmpReq.UseBinary   = true;
        tmpReq.KeepAlive   = false;
        using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
        {
            using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
            {
                try
                {
                    using (System.IO.TextReader tmpReader1 = new System.IO.StreamReader(tmpStream))
                    {
                        Res = tmpReader1.ReadToEnd();
                    }
                }
                catch (Exception e1)
                { return(Res); }

                return(Res);
            }
        }
    }
예제 #29
0
        public static Boolean FTPRemoveDirectory()
        {
            try
            {
                sDirName = sDirName.Replace("\\", "/");
                string sURI = "FTP://" + sFTPServerIP + "/" + sDirName;
                System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(sURI); //建立FTP連線
                //設定連線模式及相關參數
                myFTP.Credentials = new System.Net.NetworkCredential(sUserName, sPassWord);                       //帳密驗證
                myFTP.KeepAlive   = false;                                                                        //關閉/保持 連線
                myFTP.Timeout     = 2000;                                                                         //等待時間
                myFTP.Method      = System.Net.WebRequestMethods.Ftp.RemoveDirectory;                             //移除資料夾

                System.Net.FtpWebResponse myFtpResponse = (System.Net.FtpWebResponse)myFTP.GetResponse();         //刪除檔案/資料夾
                myFtpResponse.Close();
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("FTP File Seach Fail" + "\n" + "{0}", ex.Message);
                //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
                iFTPReTry--;
                if (iFTPReTry >= 0)
                {
                    return(FTPRemoveDirectory());
                }
                else
                {
                    return(false);
                }
            }
        }
예제 #30
0
        public static bool UploadFile(string _sourcefile, string _targetfile, string _user, string _pass)
        {
            bool up = false;

            try
            {
                System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(_targetfile);
                ftp.Credentials = new System.Net.NetworkCredential(_user, _pass);
                //userid and password for the ftp server to given

                ftp.UseBinary  = true;
                ftp.UsePassive = true;
                ftp.EnableSsl  = Core.Global.GetConfig().ConfigFTPSSL;
                ftp.Method     = System.Net.WebRequestMethods.Ftp.UploadFile;
                System.IO.FileStream fs = System.IO.File.OpenRead(_sourcefile);
                byte[] buffer           = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();
                System.IO.Stream ftpstream = ftp.GetRequestStream();
                ftpstream.Write(buffer, 0, buffer.Length);
                ftpstream.Close();
                ftp.Abort();
                up = true;
            }
            catch (Exception ex)
            {
                Core.Log.WriteLog(ex.ToString(), true);
            }
            return(up);
        }
예제 #31
0
        /// <summary>
        /// Method to upload data to an ftp server
        /// </summary>
        public void uploadData()
        {
            Console.WriteLine("*** Beginning File Upload(s) ***");

            foreach (string afile in files)
            {
                Console.WriteLine("\t...writing out " + afile);
                //create a connection object
                ftpServer = connectionInfo.Split('|')[0];
                request = (FtpWebRequest)WebRequest.Create(new Uri(ftpServer + "/" + afile));
                request.Method = WebRequestMethods.Ftp.UploadFile;

                //set username and password
                userName = connectionInfo.Split('|')[1];
                userPassword = connectionInfo.Split('|')[2];
                request.Credentials = new NetworkCredential(userName, userPassword);

                //copy contents to server
                sourceStream = new StreamReader(programFilesAt + afile);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;
                requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
                response = (FtpWebResponse)request.GetResponse();
                response.Close();
            }

            Console.WriteLine("\t File Uploads Complete");
        }
예제 #32
0
    public Queue FTPFileReader(String FileName, string username, string password)
    {
        string Res = "";
        Queue  Q1  = new Queue();

        System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(FileName);
        tmpReq.Credentials = new NetworkCredential(username, password);
        tmpReq.UsePassive  = true;
        tmpReq.UseBinary   = false;
        tmpReq.KeepAlive   = false; //close the connection when done
        using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
        {
            using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
            {
                try
                {
                    using (System.IO.TextReader tmpReader1 = new System.IO.StreamReader(tmpStream))
                    {
                        for (int a = 0; ;)
                        {
                            Q1.Enqueue(tmpReader1.ReadLine());
                        }
                    }
                }
                catch (Exception e1)
                { return(Q1); }

                return(Q1);
            }
        }
    }
예제 #33
0
파일: FTPTest.cs 프로젝트: shakasi/coding
        public bool Test()
        {
            try
            {
                System.Net.FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Url);
                //request.Method = CommandText; WebRequestMethods.Ftp.DeleteFile;
                request.Method      = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(UserName, Password);
                using (System.Net.FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    Console.WriteLine(response.BannerMessage.ToString());
                    Console.WriteLine(response.StatusCode.ToString());
                    Console.WriteLine(response.WelcomeMessage.ToString());
                    return(true);
                    //if (response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK || response.StatusCode == FtpStatusCode.OpeningData)
                    //{

                    //    return true;
                    //}
                    //else
                    //{

                    //    return false;
                    //}
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #34
0
 /// <summary>
 /// 上傳檔案至FTP
 /// </summary>
 /// <param name="FilePath">要上傳的檔案來源路徑</param>
 /// <param name="FileName">要上傳的檔案名稱</param>
 /// <returns></returns>
 public static bool Upload(string FilePath,string FileName)
 {
     Uri FtpPath = new Uri(uriServer+FileName);
     bool result = false;
     try
     {
         ftpRequest = (FtpWebRequest)WebRequest.Create(FtpPath);
         ftpRequest.Credentials = new NetworkCredential(UserName, Password);
         ftpRequest.UsePassive = false;
         ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
         ftpFileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
         byte[] uploadBytes = new byte[ftpFileStream.Length];
         ftpFileStream.Read(uploadBytes, 0, uploadBytes.Length);
         ftpStream = ftpRequest.GetRequestStream();
         ftpStream.Write(uploadBytes, 0, uploadBytes.Length);
         ftpFileStream.Close();
         ftpStream.Close();
         ftpRequest = null;
         result = true;
     }
     catch (WebException ex)
     {
         sysMessage.SystemEx(ex.Message);
     }
     return result;
 }
예제 #35
0
파일: Program.cs 프로젝트: vf503/FtpUpLoad
        //
        /// <summary>  
             /// 上传文件  
             /// </summary>  
             /// <param name="fileinfo">需要上传的文件</param>  
             /// <param name="targetDir">目标路径</param>  
             /// <param name="hostname">ftp地址</param>  
             /// <param name="username">ftp用户名</param>  
             /// <param name="password">ftp密码</param>  
             /// <returns></returns>  
        public static Boolean UploadFile(System.IO.FileInfo fileinfo, string hostname, string username, string password)
        {
            string strExtension = System.IO.Path.GetExtension(fileinfo.FullName);
            string strFileName  = "";

            strFileName = fileinfo.Name;    //获取文件的文件名  
            string URI = hostname + "/" + strFileName;

            //获取ftp对象  
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置ftp方法为上传  
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            //制定文件传输的数据类型  
            ftp.UseBinary  = true;
            ftp.UsePassive = true;


            //文件大小  
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2kb  
            const int BufferSize = 2048;

            byte[] content = new byte[BufferSize - 1 + 1];
            int    dataRead;

            //打开一个文件流(System.IO.FileStream)去读上传的文件  
            using (System.IO.FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流  
                    using (System.IO.Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB  
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    ftp        = null;
                    ftp        = GetRequest(URI, username, password);
                    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;//删除  
                    ftp.GetResponse();
                    return(false);
                }
                finally
                {
                    fs.Close();
                }
            }
        }
예제 #36
0
        public bool Archive(string ftpFileName)
        {
            bool   status       = false;
            string sourceFtpDir = _config.FtpDirecrory + "/";

            try
            {
                #region Commented
                ////List<string> listOfFile = GetAllFiles(sourceFtpDir);
                ////if (listOfFile != null && listOfFile.Count > 0)
                ////{
                ////    string latestFileName = GetLastModifiedFileName(listOfFile, sourceFtpDir);
                ////    if (latestFileName != null)
                ////    {
                //        FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(_config.Host + "/" + _config.FtpDirecrory + "/" + ftpFileName));
                //        reqFTP.UseBinary = true;
                //        reqFTP.Credentials = new NetworkCredential(_config.FtpUserName, _config.FtpPassword);
                //        reqFTP.Method = WebRequestMethods.Ftp.Rename;
                //        reqFTP.EnableSsl = _config.EnableSSL;
                //        reqFTP.RenameTo = _config.ArchiveDirectory + "/" + ftpFileName;
                //        //ftp.RenameTo = Uri.UnescapeDataString(targetUriRelative.OriginalString);
                //        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                //        status = true;
                ////    }
                ////}
                //////return response.StatusCode == FtpStatusCode.;

                //perform rename
                //FtpWebRequest ftp = GetRequest(uriSource.AbsoluteUri);
                #endregion

                Uri uriSource      = new Uri(_config.Host + "/" + _config.FtpDirecrory + "/" + ftpFileName, System.UriKind.Absolute);
                Uri uriDestination = new Uri(_config.Host + "/" + _config.ArchiveDirectory + "/" + ftpFileName, System.UriKind.Absolute);

                if (IsFileExists(uriDestination.OriginalString))
                {
                    //if file already archived delete file from archived
                    DeleteFile(uriDestination.OriginalString);
                }

                Uri targetUriRelative        = uriSource.MakeRelativeUri(uriDestination);
                System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)WebRequest.Create(uriSource.AbsoluteUri);
                ftp.Method      = WebRequestMethods.Ftp.Rename;
                ftp.Credentials = new NetworkCredential(_config.FtpUserName, _config.FtpPassword);
                ftp.EnableSsl   = _config.EnableSSL;

                ftp.RenameTo = Uri.UnescapeDataString(targetUriRelative.OriginalString);

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

                status = true;
            }
            catch (Exception)
            {
                status = false;
                throw;
            }
            return(status);
        }
예제 #37
0
        public bool Upload(FileInfo fi, string targetFilename)
        {
            string target;

            if (targetFilename.Trim() == "")
            {
                target = this.CurrentDirectory + fi.Name;
            }
            else if (targetFilename.Contains("/"))
            {
                target = AdjustDir(targetFilename);
            }
            else
            {
                target = CurrentDirectory + targetFilename;
            }

            string URI = Hostname + target;

            System.Net.FtpWebRequest ftp = GetRequest(URI);

            ftp.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftp.UseBinary = true;

            ftp.ContentLength = fi.Length;

            const int BufferSize = 2048;

            byte[] content = new byte[BufferSize - 1 + 1];
            int    dataRead;

            using (FileStream fs = fi.OpenRead())
            {
                try
                {
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                }
                finally
                {
                    fs.Close();
                }
            }


            ftp = null;
            return(true);
        }
예제 #38
0
		internal FtpWebResponse (FtpWebRequest request, Uri uri, string method, FtpStatusCode statusCode, string statusDescription)
		{
			this.request = request;
			this.uri = uri;
			this.method = method;
			this.statusCode = statusCode;
			this.statusDescription = statusDescription;
		}
예제 #39
0
        public void RemoveDirectory(string ftpAddressPath, string directoryName)
        {
            this.FtpWebRequest = (FtpWebRequest)FtpWebRequest.Create(ftpAddressPath + directoryName);
            this.FtpWebRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
            this.FtpWebRequest.Credentials = new NetworkCredential(this.Username, this.Password);

            this.FtpWebRequest.GetResponse();
        }
예제 #40
0
 private static void setProxyAuthorization(SetupConf setVariables, FtpWebRequest request)
 {
     //Proxy configurations
     if (setVariables.objProxyVariables.proxyServer.ToString() != "PlaceHolder" && setVariables.objProxyVariables.proxyPort.ToString() != "PlaceHolder")
     {
         setProxyInfo(setVariables, request);
     }
 }
예제 #41
0
파일: FTP.cs 프로젝트: lxh2014/gigade-net
 public FTP(string requestUriString, string ftpUserID, string ftpPassword)
 {
     ftpRequest = FtpWebRequest.Create(requestUriString) as FtpWebRequest;
     ftpRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
     ftpRequest.KeepAlive = false;
     ftpRequest.UsePassive = false;
     ftpRequest.UseBinary = true;
 }
예제 #42
0
파일: MyFtp.cs 프로젝트: Yowe/src
 private void Connect(string Path)
 {
     this.ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(Path));
     this.ftpRequest.UseBinary = true;
     this.ftpRequest.UsePassive = true;
     this.ftpRequest.KeepAlive = this._isKeepAlive;
     this.ftpRequest.Credentials = new NetworkCredential(this._userID, this._passWord);
 }
예제 #43
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="localDir">下载至本地路径</param>
        /// <param name="FtpDir">ftp目标文件路径</param>
        /// <param name="FtpFile">从ftp要下载的文件名</param>
        /// <param name="hostname">ftp地址即IP</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static byte[] DownloadFileBytes(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
        {
            byte[] bts;
            string URI       = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
            string tmpname   = Guid.NewGuid().ToString();
            string localfile = localDir + @"\" + tmpname;

            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
            ftp.Method     = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary  = true;
            ftp.UsePassive = true;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file
                    using (MemoryStream fs = new MemoryStream())
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int    read   = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();

                            //---
                            byte[] mbt = new byte[fs.Length];
                            fs.Read(mbt, 0, mbt.Length);

                            bts = mbt;
                            //---
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            //catch error and delete file only partially downloaded
                            fs.Close();
                            //delete target file as it's incomplete
                            File.Delete(localfile);
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }

            ftp = null;
            return(bts);
        }
예제 #44
0
        /// <summary>
        /// Upload a local source strean to the FTP server
        /// </summary>
        /// <param name="sourceStream">Source Stream</param>
        /// <param name="targetFilename">Target filename</param>
        /// <returns>
        /// 1.2 [HR] added CreateURI
        /// </returns>
        public bool Upload(Stream sourceStream, string targetFilename)
        {
            // validate the target file
            if (string.IsNullOrEmpty(targetFilename))
            {
                throw new ApplicationException("Target filename must be specified");
            }
            ;

            //perform copy
            string URI = CreateURI(targetFilename);

            System.Net.FtpWebRequest ftp = GetRequest(URI);

            //Set request to upload a file in binary
            ftp.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftp.UseBinary = true;

            //Notify FTP of the expected size
            ftp.ContentLength = sourceStream.Length;

            //create byte array to store: ensure at least 1 byte!
            const int BufferSize = 2048;

            byte[] content = new byte[BufferSize - 1 + 1];
            int    dataRead;

            //open file for reading
            using (sourceStream)
            {
                try
                {
                    sourceStream.Position = 0;
                    //open request to send
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            dataRead = sourceStream.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                    return(true);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    //ensure file closed
                    sourceStream.Close();
                    ftp = null;
                }
            }
            return(false);
        }
예제 #45
0
        /// <summary>
        /// Open Ftp file in a MemoryStream for read only. The FtpStream is copied in a MemoryStream.
        /// </summary>
        /// <param name="pStream">The ouput stream.</param>
        /// <param name="connectionGroupName">The group name for the connection</param>
        private void OpenReadFtpFile(out System.IO.Stream pStream, string connectionGroupName)
        {
            pStream = null;
            try
            {
                System.Net.FtpWebRequest lRequestFileDl = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(_filePath);
                try
                {
                    lRequestFileDl.ConnectionGroupName = connectionGroupName;
                    lRequestFileDl.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                    System.Net.FtpWebResponse lResponseFileDl = (System.Net.FtpWebResponse)lRequestFileDl.GetResponse();
                    try
                    {
                        FileInfo lDestFileInfo = new FileInfo(_destRemoteFile);

                        using (System.IO.FileStream lFileStream = lDestFileInfo.OpenWrite())
                        {
                            using (System.IO.Stream lStream = lResponseFileDl.GetResponseStream())
                            {
                                int    i     = 0;
                                byte[] bytes = new byte[2048];
                                do
                                {
                                    i = lStream.Read(bytes, 0, bytes.Length);
                                    lFileStream.Write(bytes, 0, i);
                                } while (i != 0);

                                lStream.Close();
                            }
                            lFileStream.Close();
                        }

                        pStream = lDestFileInfo.OpenRead();
                        pStream.Seek(0, System.IO.SeekOrigin.Begin);
                    }
                    finally
                    {
                        lResponseFileDl.Close();
                    }
                }
                finally
                {
                    try
                    {
                        lRequestFileDl.Abort();
                    }
                    catch (NotImplementedException)
                    {
                        // Ignore the not implemented exception
                    }
                }
            }
            catch (Exception ex)
            {
                PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, ex.Message, "PIS.Ground.Core.Data.RemoteFileClass", ex, EventIdEnum.GroundCore);
            }
        }
예제 #46
0
 /// <summary>
 /// Makes the FtpRequest object ready for a new request
 /// </summary>
 /// <param name="requestUrl"></param>
 private void SetupFtpRequest(string requestUrl)
 {
     // Set up the FtpRequest object
     this.FtpRequest = (FtpWebRequest)FtpWebRequest.Create(requestUrl);
     this.FtpRequest.Credentials = this.Credenntials;
     this.FtpRequest.KeepAlive = true;
     this.FtpRequest.UsePassive = true;
     this.FtpRequest.ConnectionGroupName = Host;
 }
예제 #47
0
파일: FtpHelp.cs 프로젝트: whuacn/CJia
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="localDir">下载至本地路径</param>
        /// <param name="FtpDir">ftp目标文件路径</param>
        /// <param name="FtpFile">从ftp要下载的文件名</param>
        /// <param name="hostname">ftp地址即IP</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
        {
            string URI       = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
            string tmpname   = Guid.NewGuid().ToString();
            string localfile = localDir + @"\" + tmpname;

            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
            ftp.Method     = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary  = true;
            ftp.UsePassive = false;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int    read   = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            fs.Close();
                            File.Delete(localfile);
                            throw;
                        }
                    }
                    responseStream.Close();
                }
                response.Close();
            }
            try
            {
                File.Delete(localDir + @"\" + FtpFile);
                File.Move(localfile, localDir + @"\" + FtpFile);
                ftp        = null;
                ftp        = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
                ftp.GetResponse();
            }
            catch (Exception ex)
            {
                File.Delete(localfile);
                throw ex;
            }
            ftp = null;
        }
예제 #48
0
		internal FtpDataStream (FtpWebRequest request, Stream stream, bool isRead)
		{
			if (request == null)
				throw new ArgumentNullException ("request");

			this.request = request;
			this.networkStream = stream;
			this.isRead = isRead;
		}
예제 #49
0
파일: FTP.cs 프로젝트: pashaiva/psub.Web
        public byte[] GetFile(string filePath)
        {
            try
            {
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + filePath);
                /* 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 */
                /* 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)
                    {

                        bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
                /* Resource Cleanup */
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;

                var nullCount = 0;
                var listInt = new List<byte>();
                var i = 1;
                foreach (var b in byteBuffer)
                {
                    if (nullCount < 3)
                    {
                        listInt.Add(b);
                    }
                    if (b == 0 && i == 0)
                        nullCount++;
                    i = b;
                }
                return listInt.ToArray();
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return new byte[1];
        }
예제 #50
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="url"></param>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public static bool DoLogin(string url,string username, string password)
 {
     Request = (FtpWebRequest)FtpWebRequest.Create(url);
     Request.Method = WebRequestMethods.Ftp.UploadFile;
     Request.Credentials = new NetworkCredential(username, password);
     Request.UsePassive = true;
     Request.UseBinary = true;
     Request.KeepAlive = false;
     return true;
 }
예제 #51
0
 public bool testConnection()
 {
     ftpRequest = (FtpWebRequest)WebRequest.Create(host);
     ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
     ftpRequest.Credentials = netCreds;
     if (ftpRequest.GetResponse() != null)
     {
         return true;
     }
     return false;
 }
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(data.adress + "/" + remoteFile);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(data.login, data.password);
            /* 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 */
            Directory.CreateDirectory(Path.GetDirectoryName(localFile));
            localFileStream = new FileStream(localFile, FileMode.Create);
            /* Buffer for the Downloaded Data */
            byte[] byteBuffer = new byte[bufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
            int totalBytesRead = bytesRead;
            /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
            while (bytesRead > 0)
            {
                if (cancel)
                {
                    localFileStream.Close();
                    ftpRequest.Abort();
                    ftpStream.Close();
                    ftpResponse.Close();
                    ftpRequest = null;
                    ftpResponse = null;
                    ftpStream = null;
                    localFileStream = null;
                    e.Cancel = true;
                    return;
                }
                localFileStream.Write(byteBuffer, 0, bytesRead);
                bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                totalBytesRead += bytesRead;
                double progress = totalBytesRead * 100.0 / fileSize;
                WorkerState state = new WorkerState(fileSize, totalBytesRead);
                worker.ReportProgress((int)progress, state);
            }

            /* Resource Cleanup */
            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
예제 #53
0
 internal FtpDataStream(NetworkStream networkStream, FtpWebRequest request, TriState writeOnly)  {
     GlobalLog.Print("FtpDataStream#" + ValidationHelper.HashString(this) + "::FtpDataStream");
     m_Readable = true;
     m_Writeable = true;
     if (writeOnly == TriState.True) {
         m_Readable = false;
     } else if (writeOnly == TriState.False) {
         m_Writeable = false;
     }
     m_NetworkStream = networkStream;
     m_Request = request;
 }
예제 #54
0
 private string GetResponseString(FtpWebRequest rq)
 {
     var response = (FtpWebResponse)rq.GetResponse();
     string res;
     using (var responseStream = response.GetResponseStream())
     {
         using (var sr = new StreamReader(responseStream))
         {
             res = sr.ReadToEnd();
         }
     }
     return res;
 }
예제 #55
0
파일: Upload.cs 프로젝트: NikxDa/TweakAPI
 /// <summary>
 /// Initializes the upload.
 /// </summary>
 public void Initialize()
 {
     request = (FtpWebRequest)FtpWebRequest.Create(upUri);
     request.Credentials = netCred;
     request.KeepAlive = true;
     request.UseBinary = true;
     request.Method = "STOR";
     reqStrm = request.GetRequestStream();
     srcFileStrm = new FileStream(srcPath, FileMode.Open, FileAccess.Read);
     buffer = new byte[8192];
     speedWatch = new Stopwatch();
     initialized = true;
 }
예제 #56
0
        //連接FTP
        private void Connect(String path)
        {

            // 根據uri創建FtpWebRequest對象
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

            // 指定數據傳輸類型
            reqFTP.UseBinary = true;

            // ftp用戶名和密碼
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);           

        }
예제 #57
0
        public static bool UploadFiles(string filePath, Uri networkPath, NetworkCredential credentials)
        {
            bool resultUpload = false;
            System.Threading.Thread.Sleep(500);
            Console.WriteLine("\nInitializing Network Connection..");

            /* si potrebbe impostare da riga di comando il keep alive, la passive mode ed il network path */
            /* progress bar? */

                //request = (FtpWebRequest)WebRequest.Create(networkPath + @"/" + Path.GetFileName(filePath));
                request = (FtpWebRequest) WebRequest.Create(networkPath + @"/"  + Path.GetFileName(filePath));
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.UsePassive = true;
                request.KeepAlive = false; /* è necessario? */
                request.Credentials = credentials;

            /* è necessario impostare la protezione ssl? */
            //request.EnableSsl = true;
                using (Stream requestStream = request.GetRequestStream())
                {

                    System.Threading.Thread.Sleep(500);
                    Console.WriteLine("\nReading the file to transfer...");
                    using (StreamReader sourceStream = new StreamReader(filePath))
                    {
                        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                        sourceStream.Close();
                        request.ContentLength = fileContents.Length;

                        System.Threading.Thread.Sleep(500);
                        Console.WriteLine("\nTransferring the file..");

                        requestStream.Write(fileContents, 0, fileContents.Length);
                        requestStream.Close();
                    }
                }

            Console.WriteLine("\nClosing connection...");

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                System.Threading.Thread.Sleep(500);
                Console.WriteLine("\nUpload of " + Path.GetFileName(filePath) + " file complete.");
                Console.WriteLine("Request status: {0}", response.StatusDescription);
                if(response.StatusDescription.Equals("226 Transfer complete.\r\n"))
                    resultUpload = true;
                response.Close();
            }

            return resultUpload;
        }
예제 #58
0
        public string[] ListDirectory(string directory)
        {

            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, directory));

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            ftpRequest.Timeout = TIMEOUT;

            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

            ftpStream = ftpResponse.GetResponseStream();

            StreamReader ftpReader = new StreamReader(ftpStream);

            string directoryRaw = null;

            try
            {
                while (ftpReader.Peek() != -1)
                {
                    //TODO: выдергиваем имя файла, доделать...
                    directoryRaw += ftpReader.ReadLine().Split(' ').Last() + "|";
                }
            }
            catch
            {
            }

            ftpReader.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;

            try
            {
                string[] directoryList = directoryRaw.Split("|".ToCharArray());
                return directoryList;
            }
            catch
            {
            }

            return new string[] { };
        }
예제 #59
-1
        //查找ftp文件夹中的文件
        public List<FtpFileInfo> GetFilesListByForder(string serverPath)
        {
            List<FtpFileInfo> lstfileName = new List<FtpFileInfo>();
            StreamReader sr = null;
            //Uri uri = new Uri("ftp://" + ftpServer + "/" + serverPath);

            Uri uri = null;
            if (serverPath != "")
                uri = new Uri(serverPath);
            else
                uri = new Uri("ftp://" + ftpServer + "/");

            try
            {
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
                if (ftpRequest == null) throw new Exception("无法打开ftp服务器连接");
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;   //列表   

                if (!IsAnonymous)
                {
                    ftpRequest.Credentials = new NetworkCredential(userName, password);
                }

                sr = new StreamReader(ftpRequest.GetResponse().GetResponseStream());
                while (!sr.EndOfStream)//读取列表
                {

                    char[] splitChar = { ' ' };
                    string temp = sr.ReadLine();
                    string[] tmpArray = temp.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);

                    if (tmpArray.Length != 9)
                    {
                        continue;
                    }
                    FtpFileInfo ffi = new FtpFileInfo();
                    ffi.IsDirectory = tmpArray[0].StartsWith("d");
                    string tempName= tmpArray[8].Replace(".","");
                    if(string.IsNullOrEmpty(tempName)) continue;

                    ffi.FileName = tmpArray[8];
                    if (serverPath != "")
                        ffi.FileFullName = serverPath + "/" + tmpArray[8];
                    else
                        ffi.FileFullName = "ftp://" + ftpServer + "/" +  tmpArray[8];
                    lstfileName.Add(ffi);
                }
            }
            catch (Exception ex)
            {
                //TODO: 异常处理.
                throw ex;
            }
            finally
            {
                if (sr != null) sr.Close();
            }
            return lstfileName;
        }
예제 #60
-1
        //download method
        public void DownloadFile(string remoteFile, string localFile)
        {
            try
            {
                //Creating the FTP Request, its settings, and login handling//
                //sends request
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(host + "/" + remoteFile));
                //log in to the server with the credentials
                ftpRequest.Credentials = new NetworkCredential(username, password);
                //specifies request type
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; 

                //toggables//
                ftpRequest.UseBinary = true; //specifies file types for transfers is binary
                ftpRequest.UsePassive = true; //specifies that the connection is from the client to the server
                ftpRequest.KeepAlive = true; //specifies we want the connetion to continue after the request is complete
                

                //Creates the communication for the server to the client and creates a io stream in which the file can be written//
                //establishes server to client communication
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                //gets the servers response stream
                ftpStream = ftpResponse.GetResponseStream(); 
                //creates a File Stream to write the downloaded file
                FileStream localFileStream = new FileStream(localFile + "\\" + remoteFile, FileMode.Create); 
                //buffer for downloading the data in bytes it is an array of bytes of the size of the remote file.
                byte[] byteBuffer = new byte[Convert.ToInt32(getFileSize(remoteFile))]; 
                //length of the bytes read in the stream
                int bytesRead = ftpStream.Read(byteBuffer, 0, Convert.ToInt32(getFileSize(remoteFile))); //bytes are read from the stream and the number of bytes read are stored into this variable
                //the stream reads in a maximum of bytes equal to the size of the remote file. these bytes are then stored into the bytebuffer array starting at the 0 position within the array.
                //the position of the stream is then advanced by the number of bytes in which are read

                try
                {
                    while (bytesRead > 0) //loops until no bytes are being read
                    {
                        //writes the byte data into the local file
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        //reads more byte data
                        bytesRead = ftpStream.Read(byteBuffer, 0, Convert.ToInt32(getFileSize(remoteFile)));
                    }
                }
                catch (Exception ex) //error message
                {
                    MessageBox.Show(ex.Message);
                }

                //closes processes and resources
                ftpResponse.Close();
                ftpStream.Close();
                localFileStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }