GetRequestStream() public method

Used to query for the Request stream of an FTP Request

public GetRequestStream ( ) : Stream
return System.IO.Stream
        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);
        }
Example #2
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;
 }
Example #3
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
            }
        }
Example #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;
        }
Example #5
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);
        }
Example #6
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);
            }
        }
Example #7
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>  
             /// <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();
                }
            }
        }
Example #8
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);
        }
Example #9
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);
        }
Example #10
0
        public static Boolean FTPUploadFile()
        {
            try
            {
                sDirName = sDirName.Replace("\\", "/");
                string sURI = "FTP://" + sFTPServerIP + "/" + sDirName + "/" + sToFileName;
                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.UseBinary   = true;                                                                         //傳輸資料型別 二進位/文字
                myFTP.UsePassive  = false;                                                                        //通訊埠接聽並等待連接
                myFTP.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;                                  //下傳檔案
                /* proxy setting (不使用proxy) */
                myFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();
                myFTP.Proxy = null;

                //上傳檔案
                System.IO.FileStream myReadStream = new System.IO.FileStream(sFromFileName, FileMode.Open, FileAccess.Read); //檔案設為讀取模式
                System.IO.Stream     myWriteStream = myFTP.GetRequestStream();                                               //資料串流設為上傳至FTP
                byte[] bBuffer = new byte[2047]; int iRead = 0;                                                              //傳輸位元初始化
                do
                {
                    iRead = myReadStream.Read(bBuffer, 0, bBuffer.Length); //讀取上傳檔案
                    myWriteStream.Write(bBuffer, 0, iRead);                //傳送資料串流
                    //Console.WriteLine("Buffer: {0} Byte", iRead);
                } while (!(iRead == 0));

                myReadStream.Flush();
                myReadStream.Close();
                myReadStream.Dispose();
                myWriteStream.Flush();
                myWriteStream.Close();
                myWriteStream.Dispose();
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("FTP Upload Fail" + "\n" + "{0}", ex.Message);
                //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
                iFTPReTry--;
                if (iFTPReTry >= 0)
                {
                    return(FTPUploadFile());
                }
                else
                {
                    return(false);
                }
            }
        }
Example #11
0
 /// <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;
 }
        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;
        }
Example #13
0
        public bool Upload2(Stream stream, string targetFilename)
        {
            string target;

            if (targetFilename.Trim() == "")
            {
                target = this.CurrentDirectory + targetFilename;
            }
            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 = stream.Length;
            byte[] content;;

            content = stream.ConvertToByte();

            try
            {
                using (Stream rs = ftp.GetRequestStream())
                {
                    rs.Write(content, 0, content.Length);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
            finally
            {
            }



            ftp = null;
            return(true);
        }
Example #14
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filePath">需要上传的文件完整路径</param>
        /// <param name="targetDir">目标路径</param>
        /// <param name="hostname">ftp地址</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static void UploadFile(string filePath, string targetDir, string hostname, string username, string password)
        {
            if (targetDir.Trim() == "")
            {
                return;
            }
            FileInfo fileinfo = new FileInfo(filePath);

            if (!FtpIsExistsFile(targetDir, hostname, username, password)) //新建targetDir目录
            {
                MakeDir(targetDir, hostname, username, password);
            }
            string URI = "ftp://" + hostname + "/" + targetDir + "/" + fileinfo.Name;

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

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

            using (FileStream fs = fileinfo.OpenRead())//打开一个文件流 (System.IO.FileStream) 去读上传的文件
            {
                try
                {
                    using (Stream rs = ftp.GetRequestStream())//把上传的文件写入流
                    {
                        do
                        {
                            dataRead = fs.Read(content, 0, BufferSize);//每次读文件流的2KB
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                }
                catch { }
                finally
                {
                    fs.Close();
                }
            }
            ftp = null;
        }
Example #15
0
        public void UploadFile()
        {
            try
            {
                _destinazione = Destinazione;

                if (!(Destinazione.StartsWith("ftp://") || Destinazione.StartsWith("ftp:\\\\")))
                {
                    _destinazione = "ftp://" + Destinazione;
                }


                System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(new Uri(_destinazione));

                ftp           = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(new Uri(_destinazione + "/" + FileName));
                ftp.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftp.UseBinary = true;

                ftp.Credentials = new System.Net.NetworkCredential(UserFTP, PwdFTP);
                FileInfo fileInf = new FileInfo(FilePath);

                ftp.ContentLength = fileInf.Length;


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

                Stream requestStream = ftp.GetRequestStream();
                contentLen = stream.Read(buff, 0, buffLength);



                while (contentLen != 0)
                {
                    requestStream.Write(buff, 0, contentLen);
                    contentLen = stream.Read(buff, 0, buffLength);
                }
                requestStream.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #16
0
        /* 1st version of the method UploadFiles, used to upload one file.  (KeepAlive = false) */
        public static bool UploadFiles(string filePath, string networkPath, NetworkCredential credentials)
        {
            bool resultUpload = false;
            System.Threading.Thread.Sleep(500);
            Console.WriteLine("\nInitializing Network Connection..");

            request = (FtpWebRequest)WebRequest.Create(UriPath(networkPath) + Path.GetFileName(filePath));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UsePassive = true;
            request.KeepAlive = false;
            request.Credentials = credentials;

            /* set ssl protection? */
            //request.EnableSsl = true;
            using (Stream requestStream = request.GetRequestStream())
            {

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

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

            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();

            }

            Console.WriteLine("\nClosing connection to {0}...", string.Format("ftp://{0}", networkPath));
            return resultUpload;
        }
Example #17
0
        private static bool Upload(string FileName, byte[] Image, string FtpUsername, string FtpPassword)
        {
            try
            {
                System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(FileName);
                clsRequest.Credentials = new System.Net.NetworkCredential(FtpUsername, FtpPassword);
                clsRequest.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                System.IO.Stream clsStream = clsRequest.GetRequestStream();
                clsStream.Write(Image, 0, Image.Length);

                clsStream.Close();
                clsStream.Dispose();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #18
0
        //**********************************************************************************************
        /// <summary>
        /// FTPサーバへファイルをアップロード
        /// </summary>
        /// <param name="s_uri">FTPサーバアドレス</param>
        /// <param name="s_user_id">ユーザーID</param>
        /// <param name="s_pass">パスワード</param>
        /// <param name="s_file_name">ファイルネーム</param>
        //**********************************************************************************************
        public void mFTP_FileUp(string s_uri, string s_user_id, string s_pass, string s_file_name)
        {
            //FtpWebRequestの作成
            System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(s_uri);
            //IDとパスワードを設定
            ftpReq.Credentials = new System.Net.NetworkCredential(s_user_id, s_pass);
            //MethodにWebRequestMethods.Ftp.UploadFile("STOR")を設定
            ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //要求の完了後に接続を閉じる
            ftpReq.KeepAlive = false;
            //ASCIIモードで転送する
            //ftpReq.UseBinary = false;
            //PASVモードを無効にする
            //ftpReq.UsePassive = false;//ファイルをアップロードするためのStreamを取得
            System.IO.Stream reqStrm = ftpReq.GetRequestStream();
            //アップロードするファイルを開く
            System.IO.FileStream Fs = new System.IO.FileStream(s_file_name,
                                                               System.IO.FileMode.Open,
                                                               System.IO.FileAccess.Read);

            //アップロードStreamに書き込む
            byte[] buffer = new byte[1024];

            while (true)
            {
                int readSize = Fs.Read(buffer, 0, buffer.Length);
                if (readSize == 0)
                {
                    break;
                }
                reqStrm.Write(buffer, 0, readSize);
            }
            Fs.Close();
            reqStrm.Close();

            //FtpWebResponseを取得
            System.Net.FtpWebResponse FtpRes =
                (System.Net.FtpWebResponse)ftpReq.GetResponse();
            //FTPサーバーから送信されたステータスを表示
            Console.WriteLine("{0}: {1}", FtpRes.StatusCode, FtpRes.StatusDescription);
            //閉じる
            FtpRes.Close();
        }
Example #19
0
        public static Result UploadFile(FTPConnectionInfo connectionInfo, string localFileName, string remoteFileName)
        {
            Result result      = new Result();
            string ftpFileName = string.Format("ftp://{0}/{1}", connectionInfo.ServerName, remoteFileName);

            FileInfo fileInfo = new FileInfo(localFileName);

            System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpFileName));
            ftpWebRequest.Credentials   = new System.Net.NetworkCredential(connectionInfo.Username, connectionInfo.Password);
            ftpWebRequest.KeepAlive     = false;
            ftpWebRequest.Timeout       = 20000;
            ftpWebRequest.Method        = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftpWebRequest.UseBinary     = true;
            ftpWebRequest.ContentLength = fileInfo.Length;
            int buffLength = 2048;

            byte[] buff = new byte[buffLength];
            System.IO.FileStream fileStream = fileInfo.OpenRead();
            try
            {
                System.IO.Stream stream = ftpWebRequest.GetRequestStream();
                int contentLen          = fileStream.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    stream.Write(buff, 0, contentLen);
                    contentLen = fileStream.Read(buff, 0, buffLength);
                }

                stream.Close();
                stream.Dispose();
                fileStream.Close();
                fileStream.Dispose();
            }
            catch (Exception e)
            {
                result.Error.Code        = ErrorCode.UPLOAD_FTP_FAIL;
                result.Error.Description = e.Message;
            }

            return(result);
        }
Example #20
0
 /// Upload File to Specified FTP Url with username and password and Upload Directory
 /// if need to upload in sub folders
 ///Base FtpUrl of FTP Server
 ///Local Filename to Upload
 ///Username of FTP Server
 ///Password of FTP Server
 ///[Optional]Specify sub Folder if any
 /// Status String from Server
 public static bool UploadFile(string ftpUrl, string userName, string password, Stream fileStream, string fileName, string
                               UploadDirectory = "")
 {
     try
     {
         System.Net.FtpWebRequest rq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpUrl + "/" + UploadDirectory + "/" + fileName);
         rq.Credentials = new System.Net.NetworkCredential(userName, password);
         rq.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
         byte[] buffer = new byte[fileStream.Length];
         fileStream.Read(buffer, 0, buffer.Length);
         fileStream.Close();
         System.IO.Stream ftpstream = rq.GetRequestStream();
         ftpstream.Write(buffer, 0, buffer.Length);
         ftpstream.Close();
     }
     catch (Exception Ex)
     {
         throw Ex;
     }
     return(true);
 }
Example #21
0
 //thanks to: http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class
 public void upload(string remoteFile, string localFile)
 {
     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.UploadFile;
     ftpStream = ftpRequest.GetRequestStream();
     FileStream localFileStream = new FileStream(localFile, FileMode.Open);
     byte[] byteBuffer = new byte[bufferSize];
     int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
     while (bytesSent != 0)
     {
         ftpStream.Write(byteBuffer, 0, bytesSent);
         bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
     }
     localFileStream.Close();
     ftpStream.Close();
     ftpRequest = null;
 }
Example #22
0
 /* Upload File */
 public void upload(string remoteFile, string localFile)
 {
     try
     {
         /* Create an FTP Request */
         ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
         /* Log in to the FTP Server with the User Name and Password Provided */
         ftpRequest.Credentials = new NetworkCredential(user, pass);
         /* When in doubt, use these options */
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         /* Specify the Type of FTP Request */
         ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
         /* Establish Return Communication with the FTP Server */
         ftpStream = ftpRequest.GetRequestStream();
         /* Open a File Stream to Read the File for Upload */
         //FileStream localFileStream = new FileStream(localFile, FileMode.Create);
         FileStream localFileStream = new FileStream(localFile, FileMode.Open);
         /* Buffer for the Downloaded Data */
         byte[] byteBuffer = new byte[bufferSize];
         int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
         /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
         try
         {
             while (bytesSent != 0)
             {
                 ftpStream.Write(byteBuffer, 0, bytesSent);
                 bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
             }
         }
         catch (Exception ex) { Console.WriteLine(ex.ToString()); }
         /* Resource Cleanup */
         localFileStream.Close();
         ftpStream.Close();
         ftpRequest = null;
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     return;
 }
Example #23
0
        public void FtpUpload(string sourceFullPath)
        {
            FileInfo sourceFileInfo = new FileInfo(sourceFullPath);

            // set up ftp
            FtpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format(@"ftp://{0}/{1}/{2}", Url, RemoteDir, sourceFileInfo.Name));
            FtpRequest.UsePassive = IsPassive;
            FtpRequest.KeepAlive = false;
            FtpRequest.Credentials = new NetworkCredential(FtpId, FtpPassword);
            FtpRequest.Method = WebRequestMethods.Ftp.UploadFile;

            byte[] fileContents = File.ReadAllBytes(sourceFullPath);
            FtpRequest.ContentLength = fileContents.Length;

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

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

            response.Close();
        }
Example #24
0
        internal void UpLoadFile(string fullFileName, string uploadedName, string dirName)
        {
            string fileName = uploadedName + new FileInfo(fullFileName).Extension;
            string uri      = string.Format("ftp://{0}:{1}/{2}/{3}", _ip, _port, dirName, fileName);

            _request = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(uri));
            //request.Credentials = new System.Net.NetworkCredential(sftpUsername, sftpPassword);
            _request.KeepAlive = false;
            _request.UseBinary = true;
            _request.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            _request.UseBinary = true;
            System.IO.FileStream fs = new System.IO.FileStream(fullFileName, System.IO.FileMode.Open);
            _request.ContentLength = fs.Length;
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            System.IO.Stream stream = _request.GetRequestStream();
            UploadObject     uo     = new UploadObject {
                stream = stream, fs = fs
            };

            stream.BeginWrite(buffer, 0, buffer.Length, UploadCallBack, uo);
        }
Example #25
0
        public static Result Connect(string server, string username, string password)
        {
            Result result = new Result();

            try
            {
                string ftpFileName = string.Format("ftp://{0}/{1}", server, "/results/test.txt");
                System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpFileName));
                ftpWebRequest.Credentials = new System.Net.NetworkCredential(username, password);
                ftpWebRequest.KeepAlive   = false;
                ftpWebRequest.Timeout     = 20000;
                ftpWebRequest.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftpWebRequest.UseBinary   = true;
                System.IO.Stream stream = ftpWebRequest.GetRequestStream();
                stream.Close();
            }
            catch (Exception e)
            {
                result.Error.Code        = ErrorCode.CONNECT_FTP_FAIL;
                result.Error.Description = e.Message;
            }

            return(result);
        }
Example #26
0
        /// <summary>
        /// Descripción: carga archivos por medio de FTP
        /// Autor: Jair Tasayco Bautista / RP0689
        /// Fecha y Hora Creación: 18/04/2016
        /// Modificado: --
        /// Fecha y hora Modificación: --
        /// </summary>
        /// <param name="ps_RutaDestino"></param>
        /// <param name="ps_NombreArchivoDestino"></param>
        /// <param name="pobj_file"></param>
        public void f_SubirArchivoFTP(string ps_NuevoNombre, FileUpload pobj_file)
        {
            //Sube archivos siempre y cuando se tenga acceso de una carpeta a otra en el servidor web
            //Sube archivos si es que se sube desde una aplicacion alojada localmente a una carpeta en uns servidor web externo
            try
            {
                string ftp           = WebConfigurationManager.AppSettings["fLoadRuta"].ToString();
                string sRutaSustento = WebConfigurationManager.AppSettings["RutaSustento"].ToString();
                string sUsuario      = WebConfigurationManager.AppSettings["fLoadUser"];
                string sContrasena   = WebConfigurationManager.AppSettings["fLoadPass"];

                System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftp + sRutaSustento + ps_NuevoNombre);
                clsRequest.Credentials = new System.Net.NetworkCredential(sUsuario, sContrasena);
                clsRequest.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                byte[]           bFile     = pobj_file.FileBytes;
                System.IO.Stream clsStream = clsRequest.GetRequestStream();
                clsStream.Write(bFile, 0, bFile.Length);
                clsStream.Close();
                clsStream.Dispose();
            }
            catch (Exception ex)
            {
            }
        }
Example #27
0
        /// <summary>
        /// Upload a local file to the FTP server
        /// </summary>
        /// <param name="fi">Source file</param>
        /// <param name="targetFilename">Target filename (optional)</param>
        /// <returns></returns>
        public bool Upload(FileInfo fi, string targetFilename)
        {
            //copy the file specified to target file: target file can be full path or just filename (uses current dir)

            //1. check target
            string target;

            if (targetFilename.Trim() == "")
            {
                //Blank target: use source filename & current dir
                target = this.CurrentDirectory + fi.Name;
            }
            else if (targetFilename.Contains("/"))
            {
                //If contains / treat as a full path
                target = AdjustDir(targetFilename);
            }
            else
            {
                //otherwise treat as filename only, use current directory
                target = CurrentDirectory + targetFilename;
            }

            string URI = Hostname + target;

            //perform copy
            UploadFTPRequest = GetRequest(URI);

            //Set request to upload a file in binary
            UploadFTPRequest.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            UploadFTPRequest.UseBinary = true;
            //Notify FTP of the expected size
            UploadFTPRequest.ContentLength = fi.Length;
            UploadFileInfo = fi;

            //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 (UploadFileStream = fi.OpenRead())
            {
                try
                {
                    //open request to send
                    using (UploadStream = UploadFTPRequest.GetRequestStream())
                    {
                        //Give Message of Command
                        NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Upload File", "STOR");
                        OnNewMessageReceived(this, e);

                        //Get File Size
                        Int64 TotalBytesUploaded = 0;
                        Int64 FileSize           = fi.Length;
                        do
                        {
                            if (UploadCanceled)
                            {
                                NewMessageEventArgs CancelMessage = new NewMessageEventArgs("RESPONSE", "Upload Canceled.", "CANCEL");
                                OnNewMessageReceived(this, CancelMessage);
                                UploadCanceled = false;
                                return(false);
                            }

                            dataRead = UploadFileStream.Read(content, 0, BufferSize);
                            UploadStream.Write(content, 0, dataRead);
                            TotalBytesUploaded += dataRead;
                            //Declare Event
                            UploadProgressChangedArgs DownloadProgress = new UploadProgressChangedArgs(TotalBytesUploaded, FileSize);

                            //Progress changed, Raise the event.
                            OnUploadProgressChanged(this, DownloadProgress);

                            System.Windows.Forms.Application.DoEvents();
                        } while (!(dataRead < BufferSize));

                        //Get Message and Raise Event
                        NewMessageEventArgs UPloadResponse = new NewMessageEventArgs("RESPONSE", "File Uploaded!", "STOR");
                        OnNewMessageReceived(this, UPloadResponse);

                        //Declare Event
                        UploadCompletedArgs Args = new UploadCompletedArgs("Successful", true);
                        //Raise Event
                        OnUploadCompleted(this, Args);

                        UploadStream.Close();
                    }
                }
                catch (Exception ex)
                {
                    //Declare Event
                    UploadCompletedArgs Args = new UploadCompletedArgs("Error: " + ex.Message, false);
                    //Raise Event
                    OnUploadCompleted(this, Args);
                }
                finally
                {
                    //ensure file closed
                    UploadFileStream.Close();
                }
            }


            UploadFTPRequest = null;
            return(true);
        }
Example #28
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(System.Windows.Controls.ProgressBar pgb_progress, FileInfo fileinfo, string targetDir, string hostname, string username, string password, int port = 21)
        {
            pgb_progress.Dispatcher.Invoke(() => { pgb_progress.Value = 3; });

            //1. check target
            string target;

            if (targetDir.Trim() == "")
            {
                return;
            }
            string filename = fileinfo.Name;

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

            //没有目录则新建一个
            if (ftpIsExistsFile(targetDir, hostname, username, password, port) == false)
            {
                MakeDir(targetDir, hostname, username, password, port);
            }

            ///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
            double persent = 0;

            int sendedCount = 0;

            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);
                            sendedCount += dataRead;
                            persent      = ((double)sendedCount) / ((double)fileinfo.Length) * 100;

                            persent = 3d + persent * ((99d - 3d) / 100d);

                            pgb_progress.Dispatcher.Invoke(() => { pgb_progress.Value = persent; });
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                }
                catch (Exception ex) { }
                finally
                {
                    fs.Close();
                }
            }
            pgb_progress.Dispatcher.Invoke(() => { pgb_progress.Value = 99; });
            ftp = null;
        }
Example #29
0
        public bool Upload(string src, string dest, int chunksize = 2048)
        {
            FileInfo inf = new FileInfo(src);
            string uri = "ftp://" + server + "/" + dest;
            Log.STR("Uploading file (" + src + ") to (" + dest + ")");
            try
            {
                Log.STR("Establishing FTP web request...");
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            }
            catch (System.Exception ex)
            {
                Log.STR("Failed with message: \"" + ex.Message + "\"");
                return false;
            }
            Log.STR("Success");

            request.Credentials = new NetworkCredential(username, password);
            request.KeepAlive = false;
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UseBinary = true;
            request.ContentLength = inf.Length;

            FileStream fs;
            try
            {
                fs = File.Open(src, FileMode.Open);
            }
            catch (System.Exception ex)
            {
                Log.STR("Failed with message: \"" + ex.Message + "\"");
                return false;
            }

            byte[] buff = new byte[chunksize];
            int contentLen;

            Log.STR("Starting file upload. File size (" + fs.Length + ") chunk size (" + chunksize + ")");
            try
            {
                Stream strm = request.GetRequestStream();
                contentLen = fs.Read(buff, 0, chunksize);
                while (contentLen > 0)
                {
                    Log.STR("Writing file chunk");
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, chunksize);
                }
                strm.Close();
                fs.Close();
            }
            catch (System.Exception ex)
            {
                Log.STR("Failed with message: \"" + ex.Message + "\"");
                return false;
            }
            Log.STR("Success.");
            return true;
        }
Example #30
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 bool UploadFile(out string msg, FileInfo fileinfo, string targetDir, string hostname, string username, string password)
        {
            msg = string.Empty;
            //1. check target
            string target;

            if (targetDir.Trim() == "")
            {
                return(false);
            }

            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;
            ftp.KeepAlive     = false;
            //此处注释掉因程序是先将重复文件删除
            //try
            //{
            //    string tp_URI = "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name;
            //    System.Net.FtpWebRequest ftp1 = GetRequest(tp_URI, username, password);
            //    ftp1 = GetRequest(tp_URI, username, password);
            //    ftp1.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
            //    ftp1.GetResponse();

            //}
            //catch(Exception e)
            //{
            //    msg = e.Message;
            //}
            //finally
            //{



            //缓冲大小设置为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) { msg = "文件上传:" + ex.Message; return(false); }
                finally
                {
                    fs.Close();
                }
            }
            ftp = null;
            //设置FTP命令
            ftp           = GetRequest(URI, username, password);
            ftp.Method    = System.Net.WebRequestMethods.Ftp.Rename; //改名
            ftp.RenameTo  = fileinfo.Name;
            ftp.KeepAlive = false;
            try
            {
                ftp.GetResponse();
            }
            catch (Exception ex)
            {
                //ftp = GetRequest(URI, username, password);
                //ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
                //ftp.GetResponse();
                //throw ex;
                msg = ex.Message;
            }
            //finally
            //{
            //    //可以对FTP文件进行删除
            //    //fileinfo.Delete();
            //}
            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;
            //}
            return(msg.Length == 0);
        }
Example #31
0
    public void UploadFile3(string filename,

                            string ShopCode)
    {
        string hostname = this.ftpServerIP;
        string username = this.ftpUserID;
        string password = this.ftpPassword;

        //1. check target
        string target;

        target = Guid.NewGuid().ToString();  //使用臨時文件名

        FileInfo fileInf = new FileInfo(filename);
        string   URI     = "FTP://" + ftpServerIP + "/" + ShopCode + "/UPLOAD/" + fileInf.Name;

        ///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 = fileInf.Length;
        //緩衝大小設置為2KB
        const int BufferSize = 2048;

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

        //打開一個文件流 (System.IO.FileStream) 去讀上傳的文件
        using (FileStream fs = fileInf.OpenRead())
        {
            try
            {
                //把上傳的文件寫入流
                using (Stream rs = ftp.GetRequestStream())
                {
                    do
                    {
                        //每次讀文件流的2KB
                        dataRead = fs.Read(content, 0, BufferSize);
                        rs.Write(content, 0, dataRead);
                    } while (dataRead > 0);
                    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 = fileInf.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
    }
Example #32
0
        // Upload File
        public void upload(string remoteFile, string localFile, BackgroundWorker worker, DoWorkEventArgs e)
        {
            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.UploadFile;

                ftpStream = ftpRequest.GetRequestStream();

                FileStream localFileStream = new FileStream(localFile, FileMode.Open);

                byte[] byteBuffer = new byte[bufferSize];
                int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);

                try
                {
                    int totalBytesSent = 0;
                    while (bytesSent != 0)
                    {
                        ftpStream.Write(byteBuffer, 0, bytesSent);
                        bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                        totalBytesSent += bytesSent;

                        var percentComplete = totalBytesSent * 100.0 / localFileStream.Length;
                        if (percentComplete > highestPercentageReached)
                        {
                            highestPercentageReached = (int)percentComplete;
                            worker.ReportProgress((int)percentComplete);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                // Housekeeping
                localFileStream.Close();
                ftpStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return;
        }
Example #33
0
        /* 2nd version of the method UploadFiles, used to upload more than one file. You can notice the same request is opened until all the files are uploaded. (KeepAlive = true) */
        public static bool[] UploadFiles(string[] filePath, string networkPath, NetworkCredential credentials)
        {
            bool[] resultUpload = new bool[filePath.Length];
            resultUpload.Populate(false);
            Console.WriteLine("\nInitializing Network Connection..");
            System.Threading.Thread.Sleep(500);
            for (int i = 0; i < filePath.Length; i++)
            {

                string currentFile = filePath[i].ToString();

                request = (FtpWebRequest)WebRequest.Create(UriPath(networkPath) + Path.GetFileName(currentFile));

                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.UsePassive = true;

                request.KeepAlive = true;
                request.Credentials = credentials;

                /* set ssl protection? */
                //request.EnableSsl = true;
                using (Stream requestStream = request.GetRequestStream())
                {

                    System.Threading.Thread.Sleep(500);

                    byte[] fileContents;
                    using (FileStream fs = new FileStream(currentFile, FileMode.Open))
                    {
                        System.Threading.Thread.Sleep(500);
                        Console.WriteLine("\nReading the file " + Path.GetFileName(currentFile) + "...");
                        fileContents = new byte[fs.Length];
                        int numBytesRead = 0;
                        int numBytesToRead = (int)fs.Length;
                        while (numBytesToRead > 0)
                        {
                            int n = fs.Read(fileContents, numBytesRead, numBytesToRead);
                            if (n == 0) break;

                            numBytesRead += n;
                            numBytesToRead -= n;

                        }
                        numBytesToRead = fileContents.Length;

                        fs.Close();
                        request.ContentLength = fileContents.Length;

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

                response = (FtpWebResponse)request.GetResponse();

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

            }
            Console.WriteLine("\nClosing connection to {0}...", string.Format("ftp://{0}", networkPath));

            response.Close();
            ((IDisposable)response).Dispose();

                /* before I used this implementation to close and dispose the response */

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

                //        response.Close();
                //    }
                //    request = null;
                //}

                return resultUpload;
        }
Example #34
0
        public StorageReturnValue StorageUpload(string pathFileNameWithExt, byte[] uploadedFile)
        {
            //copy the file specified to target file: target file can be full path or just filename (uses current dir)

            //copy the file specified to target file: target file can be full path or just filename (uses current dir)
            StorageReturnValue result = new StorageReturnValue(false, FileStorageProperties.GetInstance.WrongInitialManagement, null);

            //1. check target

            try
            {
                string target;
                if (pathFileNameWithExt.Trim() == "")
                {
                    //Blank target: use source filename & current dir
                    target = this.CurrentDirectory + pathFileNameWithExt;
                }
                else if (pathFileNameWithExt.Contains("/"))
                {
                    //If contains / treat as a full path
                    target = AdjustDir(pathFileNameWithExt);
                }
                else
                {
                    //otherwise treat as filename only, use current directory
                    target = CurrentDirectory + pathFileNameWithExt;
                }

                string URI = Hostname + target;
                //perform copy
                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 = uploadedFile.Length;

                //create byte array to store: ensure at least 1 byte!
                const int BufferSize = 2048;
                byte[]    content    = new byte[BufferSize - 1 + 1];

                int total_bytes = (int)uploadedFile.Length;

                using (Stream rs = ftp.GetRequestStream())
                {
                    while (total_bytes < uploadedFile.Length)
                    {
                        rs.Write(uploadedFile, total_bytes, BufferSize);
                        total_bytes += BufferSize;
                    }
                    rs.Close();
                }
                result = result.SetStorageReturnValue(true, string.Empty, null);
            }
            catch (Exception ex) { result = result.SetStorageReturnValue(false, ex.Message.ToString(), null); }


            return(result);
        }
Example #35
0
        public void UploadFile(string filePath, Stream fileStream)
        {
            const int bufferLength = 1;
            byte[] buffer = new byte[bufferLength];
            request = WebRequest.Create(ftp + filePath) as FtpWebRequest;
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(UserName, Password);
            request.KeepAlive = false;
            request.UseBinary = true;
            Stream requestStream = request.GetRequestStream();
            int readBytes = 0;
            do
            {
                readBytes = fileStream.Read(buffer, 0, bufferLength);
                if (readBytes != 0)
                    requestStream.Write(buffer, 0, bufferLength);
            } while (readBytes != 0);

            requestStream.Dispose();
            fileStream.Dispose();
        }
Example #36
0
        public bool Upload(HttpPostedFileBase file, string filename)
        {
            try
            {
                string uploadUrl = FtpConfig[0];

                Stream streamObj = file.InputStream;
                Byte[] buffer = new Byte[file.ContentLength];
                streamObj.Read(buffer, 0, buffer.Length);
                streamObj.Close();

                string ftpUrl = string.Format("{0}/{1}", uploadUrl, filename);
                requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
                requestObj.Method = WebRequestMethods.Ftp.UploadFile;
                requestObj.Credentials = new NetworkCredential(FtpConfig[1], FtpConfig[2]);
                Stream requestStream = requestObj.GetRequestStream();
                requestStream.Write(buffer, 0, buffer.Length);
                requestStream.Flush();
                requestStream.Close();

                return true;
            }
            catch
            {
                return false;
            }
        }
Example #37
0
        /// <summary>
        /// Upload
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <param name="localFile"></param>
        /// <returns></returns>
        public bool Upload(string remoteFile, MemoryStream localFile)
        {
            try
            {
                /* Create an FTP Request */
                _ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_host + "/" + remoteFile);

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

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

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

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


                var byteBuffer = new byte[BufferSize];
                var bytesSent = localFile.Read(byteBuffer, 0, BufferSize);
                /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
                try
                {
                    while (bytesSent != 0)
                    {
                        _ftpStream.Write(byteBuffer, 0, bytesSent);
                        bytesSent = localFile.Read(byteBuffer, 0, BufferSize);
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }

                /* Resource Cleanup */
                _ftpStream.Close();
                _ftpRequest = null;

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
Example #38
0
        //void uploadChange()
        //{
        //    if (btnUpload.InvokeRequired)
        //    {
        //        InvokeUpload btnChange = new InvokeUpload(uploadChange);
        //        btnUpload.Invoke(btnChange);
        //    }
        //    else
        //    {
        //        btnUpload.Enabled = true;
        //        //this.richTextBox1.Text = "www";
        //    }
        //}

        private static string UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
        {
            //cheack target
            string target;

            if (targetDir.Trim() == "")
            {
                return("");
            }

            target = Guid.NewGuid().ToString() + ".txt";//使用临时文件名

            string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;

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

            ftp.Credentials = new NetworkCredential(username, password);

            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];
            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)
                {
                }
                finally
                {
                    fs.Close();
                }
            }

            return(target);
        }
        private void ExecImage(string FTP, string User, string Password, Model.Local.Article Article, Model.Local.ArticleImage ArticleImage, Model.Local.ArticleImageRepository ArticleImageRepository)
        {
            Model.Prestashop.PsImageRepository     PsImageRepository     = new Model.Prestashop.PsImageRepository();
            Model.Prestashop.PsImage               PsImage               = null;
            Model.Prestashop.PsImageLangRepository PsImageLangRepository = new Model.Prestashop.PsImageLangRepository();
            Model.Prestashop.PsImageLang           PsImageLang;
            Boolean isImageLang = false;

            Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository();
            List <Model.Prestashop.PsImageType>    ListPsImageType       = PsImageTypeRepository.ListProduct(1);

            try
            {
                if (ArticleImage.Pre_Id == null)
                {
                    PsImage = new Model.Prestashop.PsImage();

                    PsImage.IDProduct = Convert.ToUInt32(Article.Pre_Id);
                    PsImage.Position  = (ushort)ExecPosition((uint)Article.Pre_Id.Value, (uint)ArticleImage.ImaArt_Position, PsImageRepository, PsImage);
                    PsImage.Cover     = ExecCover((uint)Article.Pre_Id.Value, ArticleImage.ImaArt_Default, PsImageRepository, PsImage);
                    PsImageRepository.Add(PsImage, Global.CurrentShop.IDShop);

                    #region lang
                    isImageLang = false;
                    PsImageLang = new Model.Prestashop.PsImageLang();
                    if (PsImageLangRepository.ExistImageLang(PsImage.IDImage, Core.Global.Lang))
                    {
                        PsImageLang = PsImageLangRepository.ReadImageLang(PsImage.IDImage, Core.Global.Lang);
                        isImageLang = true;
                    }
                    PsImageLang.Legend = ArticleImage.ImaArt_Name;
                    if (isImageLang == true)
                    {
                        PsImageLangRepository.Save();
                    }
                    else
                    {
                        PsImageLang.IDImage = PsImage.IDImage;
                        PsImageLang.IDLang  = Core.Global.Lang;
                        PsImageLangRepository.Add(PsImageLang);
                    }
                    // <JG> 26/12/2012 ajout insertion autres langues actives si non renseignées
                    try
                    {
                        Model.Prestashop.PsLangRepository PsLangRepository = new Model.Prestashop.PsLangRepository();
                        foreach (Model.Prestashop.PsLang PsLang in PsLangRepository.ListActive(1, Global.CurrentShop.IDShop))
                        {
                            if (!PsImageLangRepository.ExistImageLang(PsImage.IDImage, PsLang.IDLang))
                            {
                                PsImageLang = new Model.Prestashop.PsImageLang()
                                {
                                    IDImage = PsImage.IDImage,
                                    IDLang  = PsLang.IDLang,
                                    Legend  = ArticleImage.ImaArt_Name
                                };
                                PsImageLangRepository.Add(PsImageLang);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Core.Error.SendMailError(ex.ToString());
                    }
                    #endregion

                    try
                    {
                        // <JG> 10/04/2013 gestion système d'images
                        string ftpPath = "/img/p/";
                        switch (Core.Global.GetConfig().ConfigImageStorageMode)
                        {
                        case Core.Parametres.ImageStorageMode.old_system:
                            #region old_system
                            // no action on path
                            break;
                            #endregion

                        case Core.Parametres.ImageStorageMode.new_system:
                        default:
                            #region new_system

                            //System.Net.FtpWebRequest ftp_folder = null;

                            foreach (char directory in PsImage.IDImage.ToString())
                            {
                                ftpPath += directory + "/";

                                #region MyRegion
                                try
                                {
                                    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTP + ftpPath);

                                    request.Credentials = new NetworkCredential(User, Password);
                                    request.UsePassive  = true;
                                    request.UseBinary   = true;
                                    request.KeepAlive   = false;
                                    request.EnableSsl   = Core.Global.GetConfig().ConfigFTPSSL;

                                    request.Method = WebRequestMethods.Ftp.MakeDirectory;

                                    FtpWebResponse makeDirectoryResponse = (FtpWebResponse)request.GetResponse();
                                }
                                catch     //Exception ex
                                {
                                    //System.Windows.MessageBox.Show(ex.ToString());
                                }
                                #endregion

                                //try
                                //{
                                //    ftp_folder = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(FTP + ftpPath);

                                //    ftp_folder.Credentials = new System.Net.NetworkCredential(User, Password);
                                //    ftp_folder.UseBinary = true;
                                //    ftp_folder.UsePassive = true;
                                //    ftp_folder.KeepAlive = false;
                                //    ftp_folder.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory;

                                //    System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp_folder.GetResponse();
                                //    System.IO.Stream ftpStream = response.GetResponseStream();

                                //    ftpStream.Close();
                                //    response.Close();
                                //}
                                //catch(Exception ex)
                                //{
                                //    System.Windows.MessageBox.Show(ex.ToString());
                                //}
                            }
                            break;
                            #endregion
                        }

                        #region Upload des images
                        String extension = ArticleImage.GetExtension;
                        if (System.IO.File.Exists(ArticleImage.TempFileName))
                        {
                            string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system)
                                ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + ".jpg"
                                : FTP + ftpPath + PsImage.IDImage + ".jpg";

                            System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                            ftp.Credentials = new System.Net.NetworkCredential(User, Password);
                            //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(ArticleImage.TempFileName);
                            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();
                        }

                        foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType)
                        {
                            String PathImg = ArticleImage.FileName(PsImageType.Name);
                            if (System.IO.File.Exists(PathImg))
                            {
                                string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system)
                                    ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + "-" + PsImageType.Name + ".jpg"
                                    : FTP + ftpPath + PsImage.IDImage + "-" + PsImageType.Name + ".jpg";

                                System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                                ftp.Credentials = new System.Net.NetworkCredential(User, Password);
                                //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(PathImg);
                                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();
                            }
                        }
                        #endregion

                        ArticleImage.Pre_Id = Convert.ToInt32(PsImage.IDImage);
                        ArticleImageRepository.Save();
                    }
                    catch (Exception ex)
                    {
                        Core.Error.SendMailError("[UPLOAD FTP IMAGE ARTICLE]<br />" + ex.ToString());
                        PsImageLangRepository.DeleteAll(PsImageLangRepository.ListImage(PsImage.IDImage));
                        PsImageRepository.Delete(PsImage);
                    }
                }
                // option car si PAS GADA écrase infos PS
                else if (Core.Global.GetConfig().ConfigImageSynchroPositionLegende)
                {
                    PsImage = new Model.Prestashop.PsImage();
                    if (PsImageRepository.ExistImage((uint)ArticleImage.Pre_Id))
                    {
                        PsImage = PsImageRepository.ReadImage((uint)ArticleImage.Pre_Id);
                        if (PsImage.Position != (UInt16)ArticleImage.ImaArt_Position ||
                            PsImage.Cover !=
                                                                #if (PRESTASHOP_VERSION_172 || PRESTASHOP_VERSION_161)
                            ((ArticleImage.ImaArt_Default) ? Convert.ToByte(ArticleImage.ImaArt_Default) : (byte?)null))
                                                                #else
                            Convert.ToByte(ArticleImage.ImaArt_Default))
                                                                #endif
                        {
                            PsImage.Position = (ushort)ExecPosition((uint)Article.Pre_Id, (uint)ArticleImage.ImaArt_Position, PsImageRepository, PsImage);
                            PsImage.Cover    = ExecCover((uint)Article.Pre_Id, ArticleImage.ImaArt_Default, PsImageRepository, PsImage);
                            PsImageRepository.Save();

                            Model.Prestashop.PsImageShopRepository PsImageShopRepository = new Model.Prestashop.PsImageShopRepository();
                            Model.Prestashop.PsImageShop           PsImageShop           = PsImageShopRepository.ReadImage(PsImage.IDImage);
                            if (PsImageShop != null && PsImageShop.Cover !=
                                                                #if (PRESTASHOP_VERSION_160)
                                (sbyte)PsImage.Cover
                                                                #else
                                PsImage.Cover
                                                                #endif
                                )
                            {
                                                                #if (PRESTASHOP_VERSION_160)
                                PsImageShop.Cover = (sbyte)PsImage.Cover;
                                                                #else
                                PsImageShop.Cover = PsImage.Cover;
                                                                #endif
                                PsImageShopRepository.Save();
                            }
                        }

                        #region lang
                        PsImageLang = new Model.Prestashop.PsImageLang();
                        isImageLang = false;
                        if (PsImageLangRepository.ExistImageLang(PsImage.IDImage, Core.Global.Lang))
                        {
                            PsImageLang = PsImageLangRepository.ReadImageLang(PsImage.IDImage, Core.Global.Lang);
                            isImageLang = true;
                        }
                        PsImageLang.Legend = ArticleImage.ImaArt_Name;
                        if (isImageLang == true)
                        {
                            PsImageLangRepository.Save();
                        }
                        else
                        {
                            PsImageLang.IDImage = PsImage.IDImage;
                            PsImageLang.IDLang  = Core.Global.Lang;
                            PsImageLangRepository.Add(PsImageLang);
                        }
                        // <JG> 26/12/2012 ajout insertion autres langues actives si non renseignées
                        try
                        {
                            Model.Prestashop.PsLangRepository PsLangRepository = new Model.Prestashop.PsLangRepository();
                            foreach (Model.Prestashop.PsLang PsLang in PsLangRepository.ListActive(1, Global.CurrentShop.IDShop))
                            {
                                if (!PsImageLangRepository.ExistImageLang(PsImage.IDImage, PsLang.IDLang))
                                {
                                    PsImageLang = new Model.Prestashop.PsImageLang()
                                    {
                                        IDImage = PsImage.IDImage,
                                        IDLang  = PsLang.IDLang,
                                        Legend  = ArticleImage.ImaArt_Name
                                    };
                                    PsImageLangRepository.Add(PsImageLang);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Core.Error.SendMailError(ex.ToString());
                        }
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                Core.Error.SendMailError("[SYNCHRO IMAGE ARTICLE]<br />" + ex.ToString());

                if (PsImage != null)
                {
                    PsImageLangRepository.DeleteAll(PsImageLangRepository.ListImage(PsImage.IDImage));
                    PsImageRepository.Delete(PsImage);
                }
            }
        }
Example #40
0
        public void UploadData(string ftpAddressPath, string locationFile, string folder)
        {
            try
            {
                FtpWebRequest reqFTP = null;
                Stream ftpStream = null;

                string[] subDirs = folder.Split('/');

                foreach (string subDir in subDirs)
                {
                    try
                    {
                        ftpAddressPath = ftpAddressPath + subDir + "/";
                        reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpAddressPath);
                        reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                        reqFTP.UseBinary = true;
                        reqFTP.Credentials = new NetworkCredential(this.Username, this.Password);
                        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                        ftpStream = response.GetResponseStream();
                        ftpStream.Close();
                        response.Close();
                    }
                    catch (WebException ex)
                    {
                        FtpWebResponse response = (FtpWebResponse)ex.Response;
                        if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                        {
                            //Does not exist
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }

                FileInfo Finfo = new FileInfo(locationFile);
                this.FtpWebRequest = (FtpWebRequest)FtpWebRequest.Create(ftpAddressPath + Finfo.Name);
                this.FtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
                // this.FtpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                this.FtpWebRequest.Credentials = new NetworkCredential(this.Username, this.Password);

                Stream FtpStream = FtpWebRequest.GetRequestStream();
                FileStream Files = File.OpenRead(locationFile);

                int LengthBuffer = 1024;
                int ByteRead = 0;
                byte[] Buffer = new byte[LengthBuffer];

                do
                {
                    ByteRead = Files.Read(Buffer, 0, LengthBuffer);
                    FtpStream.Write(Buffer, 0, ByteRead);
                } while (ByteRead != 0);

                Files.Close();
                FtpStream.Close();
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode ==
                    FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                }
                else
                {
                    throw ex;
                }
            }
        }
Example #41
0
        ///* Download File */
        //public string download(string remoteFile, string localFile)
        //{
        //    string serr = "";
        //    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)
        //        {
        //            serr = "{error}" + ex.Message;
        //        }
        //        /* Resource Cleanup */
        //        localFileStream.Close();
        //        ftpStream.Close();
        //        ftpResponse.Close();
        //        ftpRequest = null;
        //    }
        //    catch (Exception ex)
        //    {
        //        if (string.IsNullOrWhiteSpace(serr))
        //            serr = "{error}" + ex.Message;
        //        else
        //            serr = serr + "\n" + ex.Message;
        //    }
        //    return serr;
        //}
        /* Upload File */
        public string upload(string remoteFile, string localFile)
        {
            string serr = "";
            try
            {
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                /* When in doubt, use these options */
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                /* Establish Return Communication with the FTP Server */
                ftpStream = ftpRequest.GetRequestStream();
                /* Open a File Stream to Read the File for Upload */
                FileStream localFileStream = new FileStream(localFile, FileMode.Open);
                FileInfo fi = new FileInfo(localFile);
                long size = fi.Length;
                if (UploadEventHandler != null)
                    UploadEventHandler(this, new UploadEventArgs() { Max = size, Cur = 0 });
                /* Buffer for the Downloaded Data */
                byte[] byteBuffer = new byte[bufferSize];
                int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
                int totalRead = bytesSent;
                try
                {
                    while (bytesSent != 0)
                    {
                        ftpStream.Write(byteBuffer, 0, bytesSent);

                        if (UploadEventHandler != null)
                            UploadEventHandler(this, new UploadEventArgs() { Max = size, Cur = totalRead });

                        bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);

                        totalRead = totalRead + bytesSent;
                    }
                }
                catch (Exception ex)
                {
                    serr = "{error}" + ex.Message;
                }
                /* Resource Cleanup */
                localFileStream.Close();
                ftpStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                if (string.IsNullOrWhiteSpace(serr))
                    serr = "{error}" + ex.Message;
                else
                    serr = serr + "\n" + ex.Message;
            }
            return serr;
        }
Example #42
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");
        }
        //uploadFile method
        public void UploadFile(string localFile)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(localFile);
                //for the most part the same as download
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(host + "/" + fileInfo.Name));
                ftpRequest.Credentials = new NetworkCredential(username, password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = false;
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; //method is now upload
                ftpStream = ftpRequest.GetRequestStream();
                FileStream localFileStream = fileInfo.OpenRead(); //stream to upload
                byte[] bytebuffer = new byte[localFileStream.Length]; //the length of the array is the size of the local file
                int bytesSend = localFileStream.Read(bytebuffer, 0, (int)localFileStream.Length); //reads in byte data from the local file with the max count of the length of the file

                try
                {
                    while (bytesSend != 0) //uploads until the transfer is complete. when there are no more bytes left to send
                    {
                        //writes to the ftpStream for the upload
                        ftpStream.Write(bytebuffer, 0, bytesSend);
                        //reads more bytes to the buffer
                        bytesSend = localFileStream.Read(bytebuffer, 0, (int)localFileStream.Length);

                    }
                }


                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                localFileStream.Close();
                ftpStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #44
0
        /// <summary>
        /// Upload a local file to the FTP server
        /// </summary>
        /// <param name="fi">Source file</param>
        /// <param name="targetFilename">Target filename (optional)</param>
        /// <returns></returns>
        public bool Upload(FileInfo fi, string targetFilename)
        {
            //copy the file specified to target file: target file can be full path or just filename (uses current dir)
            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;

            //perform copy
            UploadFTPRequest = GetRequest(URI);

            //Set request to upload a file in binary
            UploadFTPRequest.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            UploadFTPRequest.UseBinary = true;
            //Notify FTP of the expected size
            UploadFTPRequest.ContentLength = fi.Length;
            UploadFileInfo = fi;

            //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 (UploadFileStream = fi.OpenRead())
            {
                try
                {
                    using (UploadStream = UploadFTPRequest.GetRequestStream())
                    {
                        Int64 TotalBytesUploaded = 0;
                        Int64 FileSize           = fi.Length;
                        do
                        {
                            dataRead = UploadFileStream.Read(content, 0, BufferSize);
                            UploadStream.Write(content, 0, dataRead);
                            TotalBytesUploaded += dataRead;
                            //Declare Event
                            UploadProgressChangedArgs DownloadProgress = new UploadProgressChangedArgs(TotalBytesUploaded, FileSize);
                            //Progress changed, Raise the event.
                            OnUploadProgressChanged(this, DownloadProgress);
                            System.Windows.Forms.Application.DoEvents();
                        }while (!(dataRead < BufferSize));
                        UploadCompletedArgs Args = new UploadCompletedArgs("Successful", true);
                        //Raise Event
                        OnUploadCompleted(this, Args);
                        UploadStream.Close();
                    }
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    UploadFileStream.Close();
                }
            }
            UploadFTPRequest = null;
            return(true);
        }
Example #45
0
        //метод протокола FTP STOR для загрузки файла на FTP-сервер
        public void UploadFile(string path, string fileName)
        {
            //для имени файла
            string shortName = fileName.Remove(0, fileName.LastIndexOf("\\") + 1);

            FileStream uploadedFile = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + _Host + path + shortName);
            ftpRequest.Credentials = new NetworkCredential(_UserName, _Password);
            ftpRequest.EnableSsl = _UseSSL;
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

            //Буфер для загружаемых данных
            byte[] file_to_bytes = new byte[uploadedFile.Length];
            //Считываем данные в буфер
            uploadedFile.Read(file_to_bytes, 0, file_to_bytes.Length);

            uploadedFile.Close();

            //Поток для загрузки файла
            Stream writer = ftpRequest.GetRequestStream();

            writer.Write(file_to_bytes, 0, file_to_bytes.Length);
            writer.Close();
        }
Example #46
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, bool fugai)
        {
            targetDir = targetDir.Replace("\\", "/");
            //判断是否有该文件夹
            CreateDirectory(targetDir);
            //if(DirectoryExist(targetDir,)
            //判断是否有该文件
            if (FileExist(targetDir, fileinfo.Name))
            {
                if (fugai)
                {
                    DeleteFile(targetDir + "/" + fileinfo.Name);
                }
                else
                {
                    return;
                }
            }


            //1. check target
            string target = fileinfo.Name;

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


            string URI = GetURI() + "/" + targetDir + "/" + target;

            ///WebClient webcl = new WebClient();


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

            //设置FTP命令
            ftp.Method     = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftp.UseBinary  = true;
            ftp.UsePassive = true;

            //告诉ftp文件大小
            ftp.ContentLength = fileinfo.Length;

            const int BufferSize = 2048;

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

            //上传文件内容
            using (FileStream fs = fileinfo.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) { ex.ToLog(); }
                finally
                {
                    fs.Close();
                }
            }

            //ftp = null;

            ////设置FTP命令
            //ftp = GetRequest(URI);
            //ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
            //ftp.RenameTo = fileinfo.Name;
            //try
            //{
            //    ftp.GetResponse();
            //}
            //catch (Exception ex)
            //{
            //    ftp = GetRequest(URI);
            //    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
            //    ftp.GetResponse();
            //    throw ex;
            //}
            //finally
            //{

            //    //fileinfo.Delete();
            //}


            // 可以记录一个日志  "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
            ftp = null;
        }
Example #47
0
        private void executeUploadFile()
        {
            FileInfo file = new FileInfo(tempname);
            String uri = "ftp://" + host + "/" + filename;

            req = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

            req.Credentials = new NetworkCredential(user, pass);
            req.KeepAlive = false;
            req.Method = WebRequestMethods.Ftp.UploadFile;
            req.UseBinary = true;
            req.ContentLength = file.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            FileStream fs = file.OpenRead();

            try
            {
                Stream strm = req.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);

                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                strm.Close();
                fs.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Image failed to upload.", "ScreenGrab");
            }
            prog.SafeInvoke(() => { prog.Close(); });
        }
Example #48
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileinfo">需要上传的文件</param>
        /// <param name="filename">需要上传的文件名称</param>
        /// <param name="fileDeptempent">需要上传的文件部门名称,按照部门划分上传路径文件夹</param>
        public void UploadFile(MemoryStream fileinfo, string filename,string fileDeptempent)
        {
            string URI = string.Format("ftp://{0}/{1}/{2}", ftpServerIP, fileDeptempent, filename);

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(URI));
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.ContentLength = fileinfo.Length;

            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
            //FileStream fs = fileinfo.OpenRead();
            Stream strm = null;
            //重要
            fileinfo.Position = 0;
            try
            {
                // 把上传的文件写入流
                strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb
                contentLen = fileinfo.Read(buff, 0, buffLength);
                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fileinfo.Read(buff, 0, buffLength);
                }

            }
            catch (Exception ex)
            {

            }
            finally
            {
                // 关闭两个流
                if (strm != null)
                    strm.Close();
            }
        }
Example #49
0
        /* Upload File */
        public void upload( string localFile,string remoteFile)
        {
            if (remoteFile == "")
            {
                remoteFile = Path.GetFileName(localFile);
            }
            remoteFile=remoteFile.Replace('\\','/');
            remoteFile=remoteFile.Replace("\\\"","");
            // Is remoteFile a path without the filename?
            int last_slash=remoteFile.LastIndexOfAny(new char[] { '/','\\' });
            if(last_slash==remoteFile.Length-1)
            {
                remoteFile+=filenameOnly(localFile);
            }
            string finalFile=host + "/" + remoteFile;
            string tempFile=finalFile+"_temp";
            // Create an FTP Request
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(tempFile);
            // Log in to the FTP Server with the User Name and Password Provided
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            // When in doubt, use these options
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            // Specify the Type of FTP Request
            ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
            // Establish Return Communication with the FTP Server
            ftpStream = ftpRequest.GetRequestStream();
            localFile=localFile.Replace('/','\\');
            // Open a File Stream to Read the File for Upload
            FileStream localFileStream = new FileStream(localFile, FileMode.Open);
            // Buffer for the Downloaded Data
            byte[] byteBuffer = new byte[bufferSize];
            int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
            // Upload the File by Sending the Buffered Data Until the Transfer is Complete
            try
            {
                while (bytesSent != 0)
                {
                    ftpStream.Write(byteBuffer, 0, bytesSent);
                    bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            // Resource Cleanup
            localFileStream.Close();
            ftpStream.Close();
            ftpRequest = null;

            string checkFile=localFile+"_check";
            download(tempFile,checkFile);

            byte[] fileHash;
            byte[] checkHash;
            var md5=MD5.Create();

            using(var stream=File.OpenRead(localFile))
            {
                fileHash=md5.ComputeHash(stream);
            }
            using(var stream=File.OpenRead(checkFile))
            {
                checkHash=md5.ComputeHash(stream);
            }
            var file_ok=checkHash.SequenceEqual(fileHash); // true
            if(!file_ok)
                throw new Exception("File upload check failed for: "+localFile);

            rename(tempFile,finalFile);

            File.Delete(checkFile);
        }
        private static bool TransferFiletoFTP(string ftpAddress, string userID, string password, string jobFile, bool deleteFileAfterTransfer)
        {
            bool isTransferSuccessfull = false;

            DateTime dtJobReleaseStart = DateTime.Now;

            try
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(jobFile);

                // Create FtpWebRequest object from the Uri provided
                System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpAddress));

                // Provide the WebPermission Credintials
                ftpWebRequest.Credentials = new System.Net.NetworkCredential(userID, password);
                ftpWebRequest.Proxy       = null;
                //ftpWebRequest.ConnectionGroupName = jobFile;
                // By default KeepAlive is true, where the control connection is not closed
                // after a command is executed.
                ftpWebRequest.KeepAlive = false;

                // set timeout for 20 seconds
                ftpWebRequest.Timeout = 30000;

                // Specify the command to be executed.
                ftpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

                // Specify the data transfer type.
                ftpWebRequest.UseBinary = true;

                // Notify the server about the size of the uploaded file
                ftpWebRequest.ContentLength = fileInfo.Length;

                // The buffer size is set to 4MB
                int    buffLength = 4 * 1024 * 1024;
                byte[] buff       = new byte[buffLength];

                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                System.IO.FileStream fileStream = fileInfo.OpenRead();


                // Stream to which the file to be upload is written
                System.IO.Stream stream = ftpWebRequest.GetRequestStream();

                // Read from the file stream 4MB at a time
                int contentLen = fileStream.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    stream.Write(buff, 0, contentLen);
                    contentLen = fileStream.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                stream.Close();
                stream.Dispose();
                fileStream.Close();
                fileStream.Dispose();
                isTransferSuccessfull = true;
            }
            catch (Exception ex)
            {
                isTransferSuccessfull = false;
                //MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Exception, ex.Message, "Restart the Print Data Provider Service", ex.Message, ex.StackTrace);
            }
            finally
            {
                DateTime dtJobReleaseEnd = DateTime.Now;
                //UpdateJobReleaseTimings(serviceName, drPrintJob["JOB_FILE"].ToString().Replace("_PDFinal", "_PD"), dtJobReleaseStart, dtJobReleaseEnd, jobDBID);

                if (deleteFileAfterTransfer)
                {
                    //var tskDeleteFile = Task.Factory.StartNew(() => DeletePrintJobsFile(serviceName, jobFileName));
                }
            }
            return(isTransferSuccessfull);
        }
        public void uploadBuffer(string fileName, byte[] buffer)
        {
            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.UploadFile;
                /* Establish Return Communication with the FTP Server */
                ftpStream = ftpRequest.GetRequestStream();
                /* Open a File Stream to Read the File for Upload */

                try
                {
                    ftpStream.Write(buffer, 0, buffer.Length);
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }

                ftpStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return;
        }
Example #52
0
 /// <�ϴ�>
 /// �ϴ�
 /// </�ϴ�>
 /// <param name="filename">�ϴ����ļ�</param>
 /// <param name="ftpServerIP"></param>
 /// <param name="ftpUserID"></param>
 /// <param name="ftpPassword"></param>
 /// <param name="pb"></param>
 /// <param name="path"></param>
 /// <returns>�ϴ��ɹ�����True</returns>
 public bool Upload(string filename, string ftpServerIP, string ftpUserID, string ftpPassword, ToolStripProgressBar pb,string path)
 {
     if (path == null)
         path = "";
     bool success = true;
     FileInfo fileInf = new FileInfo(filename);
     int allbye = (int)(fileInf.Length/1024 + 1);
     long startbye = 0;
     pb.Maximum = allbye;
     pb.Minimum = 0;
     string newFileName;
     if (fileInf.Name.IndexOf("#") == -1)
     {
         newFileName =QCKG(fileInf.Name);
     }
     else
     {
         newFileName = fileInf.Name.Replace("#", "��");
         newFileName = QCKG(newFileName);
     }
     string uri;
     if (path.Length == 0)
         uri = "ftp://" + ftpServerIP + "/" + newFileName;
     else
         uri = "ftp://" + ftpServerIP + "/" + path + newFileName;
     FtpWebRequest reqFTP;
     // ����uri����FtpWebRequest����
     reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
     // ftp�û���������
     reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
     // Ĭ��Ϊtrue�����Ӳ��ᱻ�ر�
     // ��һ������֮��ִ��
     reqFTP.KeepAlive = false;
     // ָ��ִ��ʲô����
     reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
     // ָ�����ݴ�������
     reqFTP.UseBinary = true;
     // �ϴ��ļ�ʱ֪ͨ�������ļ��Ĵ�С
     reqFTP.ContentLength = fileInf.Length;
     int buffLength = 2048;// �����С����Ϊ2kb
     byte[] buff = new byte[buffLength];
     // ��һ���ļ��� (System.IO.FileStream) ȥ���ϴ����ļ�
     FileStream fs= fileInf.OpenRead();
     try
     {
         // ���ϴ����ļ�д����
         Stream strm = reqFTP.GetRequestStream();
         // ÿ�ζ��ļ�����2kb
         int contentLen = fs.Read(buff, 0, buffLength);
         // ������û�н���
         while (contentLen != 0)
         {
             // �����ݴ�file stream д�� upload stream
             strm.Write(buff, 0, contentLen);
             contentLen = fs.Read(buff, 0, buffLength);
             startbye += contentLen;
             pb.Value = (int)(startbye/1024 + 1);
         }
         // �ر�������
         strm.Close();
         fs.Close();
      }
      catch
      {
          success = false;
      }
      return success;
 }
Example #53
0
        private void UploadThread(Object stateInfo)
        {
            // No state object was passed to QueueUserWorkItem, so 
            // stateInfo is null.            
            var task = (UploadTask)stateInfo;


            if (task.RemoteDir == null)
                task.RemoteDir = "";
            FileInfo fileInf = new FileInfo(task.FileName);

            var transferEventArgs = new TransferEventArgs(task.FileName, task.RemoteDir, fileInf.Length);
            if (FileUploadBegin != null)
            {
                FileUploadBegin(this, transferEventArgs);
            }

            int allbye = (int)(fileInf.Length / 1024 + 1);
            string newFileName;
            if (fileInf.Name.IndexOf("#") == -1)
            {
                newFileName = QCKG(fileInf.Name);
            }
            else
            {
                newFileName = fileInf.Name.Replace("#", "#");
                newFileName = QCKG(newFileName);
            }
            string uri;
            if (task.RemoteDir.Length == 0)
                uri = "ftp://" + ftpHost + "/" + newFileName;
            else
                uri = "ftp://" + ftpHost + "/" + task.RemoteDir + "/" + newFileName;

            FtpWebRequest reqFTP;
            // 根据uri创建FtpWebRequest对象 
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
            reqFTP.Proxy = null;
            reqFTP.KeepAlive = true;
            // ftp用户名和密码 
            reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
            // 默认为true,连接不会被关闭 
            // 在一个命令之后被执行 
            reqFTP.KeepAlive = false;
            // 指定执行什么命令 
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 指定数据传输类型 
            reqFTP.UseBinary = true;
            // 上传文件时通知服务器文件的大小 
            reqFTP.ContentLength = fileInf.Length;
            //int buffLength = 2048;// 缓冲大小设置为2kb 
            int buffLength = 1024 * 1024; 

            byte[] buff = new byte[buffLength];
            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 
            FileStream fs = fileInf.OpenRead();
            try
            {
                long startbye = 0;
                // 把上传的文件写入流 
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb 
                int contentLen = fs.Read(buff, 0, buffLength);
                // 流内容没有结束 
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream 
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                    startbye += contentLen;
                    //pb.Value = (int)(startbye / 1024 + 1);
                    if (FileUploadPorgress != null)
                    {
                        FileUploadPorgress(this, new TransferProgressEventArgs(task.FileName, task.RemoteDir, fileInf.Length, startbye));
                    }
                }
                // 关闭两个流 
                strm.Close();
                fs.Close();

                if(FileUploadFinished !=null)
                {
                    FileUploadFinished(this, transferEventArgs);
                }
            }
            catch(Exception e)
            {
                if(FileUploadFailed !=null)
                {
                    FileUploadFailed(this, transferEventArgs);
                }
            }
        }
Example #54
0
            /// <summary>
            /// Hàm upload file
            /// </summary>
            public void UpLoad(string filename, string dir)
            {
                FileInfo fileInf = new FileInfo(filename);
                string uri = "ftp://" + FTPServerIP + "/" + fileInf.Name;
                FtpWebRequest reqFTP;
                string[] dirs = dir.Split('/');
                string des = "";

                bool needCheck = true;
                foreach (string d in dirs)
                {
                    if (needCheck)
                    {
                        if (!IsExist(d))
                        {
                            MakeDir(d);
                            needCheck = false;
                        }
                    }
                    else
                    {
                        MakeDir(d);
                    }
                    des += "/" + d;

                }

                // Create FtpWebRequest object from the Uri provided
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPServerIP + "/" + dir + "/" + fileInf.Name));

                // Provide the WebPermission Credintials
                reqFTP.Credentials = new NetworkCredential(FTPUserID, FTPassword);

                // By default KeepAlive is true, where the control connection is not closed
                // after a command is executed.
                reqFTP.KeepAlive = false;

                // Specify the command to be executed.
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

                // Specify the data transfer type.
                reqFTP.UseBinary = true;

                // Notify the server about the size of the uploaded file
                reqFTP.ContentLength = fileInf.Length;

                // The buffer size is set to 2kb
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;

                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                FileStream fs = fileInf.OpenRead();

                try
                {
                    // Stream to which the file to be upload is written
                    Stream strm = reqFTP.GetRequestStream();

                    // Read from the file stream 2kb at a time
                    contentLen = fs.Read(buff, 0, buffLength);

                    // Till Stream content ends
                    while (contentLen != 0)
                    {
                        // Write Content from the file stream to the FTP Upload Stream
                        strm.Write(buff, 0, contentLen);
                        contentLen = fs.Read(buff, 0, buffLength);
                    }

                    // Close the file stream and the Request Stream
                    strm.Close();
                    fs.Close();
                }
                catch (Exception)
                {

                }

            }
        public static void UploadFile(string _FileName, string _UploadPath, string _FTPUser, string _FTPPass)
        {
            System.IO.FileInfo _FileInfo = new System.IO.FileInfo(_FileName);

            // Create FtpWebRequest object from the Uri provided
            System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(_UploadPath));

            // Provide the WebPermission Credentials
            _FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass);
            _FtpWebRequest.Proxy       = null;
            //_FtpWebRequest.ConnectionGroupName = _FileName;
            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            _FtpWebRequest.KeepAlive = false;

            // set timeout for 20 seconds
            _FtpWebRequest.Timeout = 30000;

            // Specify the command to be executed.
            _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            _FtpWebRequest.UseBinary = true;

            // Notify the server about the size of the uploaded file
            _FtpWebRequest.ContentLength = _FileInfo.Length;

            // The buffer size is set to 2kb
            int buffLength = 1024 * 4;

            byte[] buff = new byte[buffLength];

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            System.IO.FileStream _FileStream = _FileInfo.OpenRead();

            // Stream to which the file to be upload is written
            System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();

            try
            {
                // Read from the file stream 2kb at a time
                int contentLen = _FileStream.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    _Stream.Write(buff, 0, contentLen);
                    contentLen = _FileStream.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                _Stream.Close();
                _Stream.Dispose();
                _FileStream.Close();
                _FileStream.Dispose();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (_Stream != null)
                {
                    _Stream.Close();
                    _Stream.Dispose();
                }
                if (_FileStream != null)
                {
                    _FileStream.Close();
                    _FileStream.Dispose();
                }
                _FtpWebRequest = null;
            }
        }
Example #56
0
 /// <上传>
 /// 上传
 /// </上传>
 /// <param name="filename">上传的文件</param>
 /// <param name="ftpServerIP"></param>
 /// <param name="ftpUserID"></param>
 /// <param name="ftpPassword"></param>
 /// <param name="pb"></param>
 /// <param name="path"></param>
 /// <returns>上传成功返回True</returns>
 public bool Upload(string filename, string ftpServerIP, string ftpUserID, string ftpPassword, ToolStripProgressBar pb,string path)
 {
     if (path == null)
         path = "";
     bool success = true;
     FileInfo fileInf = new FileInfo(filename);
     int allbye = (int)(fileInf.Length/1024 + 1);
     long startbye = 0;
     pb.Maximum = allbye;
     pb.Minimum = 0;
     string newFileName;
     if (fileInf.Name.IndexOf("#") == -1)
     {
         newFileName =QCKG(fileInf.Name);
     }
     else
     {
         newFileName = fileInf.Name.Replace("#", "#");
         newFileName = QCKG(newFileName);
     }
     string uri;
     if (path.Length == 0)
         uri = "ftp://" + ftpServerIP + "/" + newFileName;
     else
         uri = "ftp://" + ftpServerIP + "/" + path + newFileName;
     FtpWebRequest reqFTP;
     // 根据uri创建FtpWebRequest对象 
     reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
     // ftp用户名和密码 
     reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
     // 默认为true,连接不会被关闭 
     // 在一个命令之后被执行 
     reqFTP.KeepAlive = false;
     // 指定执行什么命令 
     reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
     // 指定数据传输类型 
     reqFTP.UseBinary = true;
     // 上传文件时通知服务器文件的大小 
     reqFTP.ContentLength = fileInf.Length;
     int buffLength = 2048;// 缓冲大小设置为2kb 
     byte[] buff = new byte[buffLength];
     // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 
     FileStream fs= fileInf.OpenRead();
     try
     {
         // 把上传的文件写入流 
         Stream strm = reqFTP.GetRequestStream();
         // 每次读文件流的2kb 
         int contentLen = fs.Read(buff, 0, buffLength);
         // 流内容没有结束 
         while (contentLen != 0)
         {
             // 把内容从file stream 写入 upload stream 
             strm.Write(buff, 0, contentLen);
             contentLen = fs.Read(buff, 0, buffLength);
             startbye += contentLen;
             pb.Value = (int)(startbye/1024 + 1);
         }
         // 关闭两个流 
         strm.Close();
         fs.Close();
      }
      catch
      {
          success = false;
      }
      return success;
 }
Example #57
0
        /// <summary>
        /// Upload a local file to the FTP server
        /// </summary>
        /// <param name="fi">Source file</param>
        /// <param name="targetFilename">Target filename (optional)</param>
        /// <returns></returns>
        public bool Upload(FileInfo fi, string targetFilename)
        {
            //copy the file specified to target file: target file can be full path or just filename (uses current dir)

            //1. check target
            string target;

            if (targetFilename.Trim() == "")
            {
                //Blank target: use source filename & current dir
                target = this.CurrentDirectory + fi.Name;
            }
            else if (targetFilename.Contains("/"))
            {
                //If contains / treat as a full path
                target = AdjustDir(targetFilename);
            }
            else
            {
                //otherwise treat as filename only, use current directory
                target = CurrentDirectory + targetFilename;
            }

            string URI = Hostname + target;

            //perform copy
            System.Net.FtpWebRequest ftp = GetRequest(URI).Result;

            //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 = fi.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 (FileStream fs = fi.OpenRead())
            {
                try
                {
                    //open request to send
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    //ensure file closed
                    fs.Close();
                }
            }


            ftp = null;
            return(true);
        }
Example #58
0
        public bool Upload(string filename, byte[] buffer)
        {
            try
            {
                string uploadUrl = FtpConfig[0];

                string ftpUrl = string.Format("{0}/{1}", uploadUrl, filename);
                requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
                requestObj.Method = WebRequestMethods.Ftp.UploadFile;
                requestObj.Credentials = new NetworkCredential(FtpConfig[1], FtpConfig[2]);
                Stream requestStream = requestObj.GetRequestStream();
                requestStream.Write(buffer, 0, buffer.Length);
                requestStream.Flush();
                requestStream.Close();

                return true;
            }
            catch
            {
                return false;
            }
        }