當前位置: 首頁>>代碼示例>>C#>>正文


C# FtpWebRequest.GetRequestStream方法代碼示例

本文整理匯總了C#中System.Net.FtpWebRequest.GetRequestStream方法的典型用法代碼示例。如果您正苦於以下問題:C# FtpWebRequest.GetRequestStream方法的具體用法?C# FtpWebRequest.GetRequestStream怎麽用?C# FtpWebRequest.GetRequestStream使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Net.FtpWebRequest的用法示例。


在下文中一共展示了FtpWebRequest.GetRequestStream方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: copyToServer

        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;
        }
開發者ID:keltie21,項目名稱:PAXperiments,代碼行數:33,代碼來源:FTPconnection.cs

示例2: Upload

 /// <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;
 }
開發者ID:coreychen71,項目名稱:EWPCB-Project,代碼行數:32,代碼來源:ConnFTP.cs

示例3: Initialize

 /// <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;
 }
開發者ID:NikxDa,項目名稱:TweakAPI,代碼行數:16,代碼來源:Upload.cs

示例4: UploadFiles

        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;
        }
開發者ID:sicil1ano,項目名稱:FtpUploader,代碼行數:51,代碼來源:FtpHelperSingleFile.cs

示例5: UploadFiles

        /* 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;
        }
開發者ID:sicil1ano,項目名稱:FtpUploader,代碼行數:45,代碼來源:FtpHelper.cs

示例6: upload

 //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;
 }
開發者ID:not1ce111,項目名稱:Spedit,代碼行數:22,代碼來源:FTP.cs

示例7: upload

 /* 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;
 }
開發者ID:martyn-m,項目名稱:pivbuff-test,代碼行數:41,代碼來源:Ftp.cs

示例8: FtpUpload

        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();
        }
開發者ID:rocker8942,項目名稱:Utility,代碼行數:22,代碼來源:FtpClient.cs

示例9: UploadFile

        /// <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();
            }
        }
開發者ID:SaintLoong,項目名稱:Framework,代碼行數:51,代碼來源:FtpHelper.cs

示例10: executeUploadFile

        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(); });
        }
開發者ID:justinappler,項目名稱:screengrab,代碼行數:38,代碼來源:FTPUtility.cs

示例11: UploadFile

        //метод протокола 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();
        }
開發者ID:Oleksandr93,項目名稱:MyWorks,代碼行數:26,代碼來源:FtpClient.cs

示例12: UploadFile

        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();
        }
開發者ID:ReinhardHsu,項目名稱:devfw,代碼行數:21,代碼來源:FtpClient.cs

示例13: Upload

        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;
            }
        }
開發者ID:shadowzcw,項目名稱:nCommon,代碼行數:27,代碼來源:FTPUploader.cs

示例14: Upload

        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;
        }
開發者ID:drsoxen,項目名稱:Cloud-Runner,代碼行數:59,代碼來源:Host.cs

示例15: upload

        /* 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);
        }
開發者ID:simul,項目名稱:cruise_control,代碼行數:73,代碼來源:Ftp.cs


注:本文中的System.Net.FtpWebRequest.GetRequestStream方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。