コード例 #1
0
        public static async Task <string> PushFile()
        {
            StringBuilder strBuilder = new StringBuilder();
            FtpWebRequest req        = (FtpWebRequest)WebRequest.Create("ftp://localhost/Program.cs");

            req.Method = WebRequestMethods.Ftp.UploadFile;

            req.Credentials = new NetworkCredential("s_burns", "test_password");
            req.UsePassive  = true;

            byte[] fileBytes;

            using (var reader = new StreamReader(@"Program.cs")) {
                fileBytes = Encoding.ASCII.GetBytes(reader.ReadToEnd());
            }

            req.ContentLength = fileBytes.Length;

            using (var reqStream = await req.GetRequestStreamAsync()) {
                await reqStream.WriteAsync(fileBytes, 0, fileBytes.Length);
            }

            using (FtpWebResponse resp = (FtpWebResponse)req.GetResponse()) {
                strBuilder.Append(resp.StatusDescription);
            }

            return(strBuilder.ToString());
        }
コード例 #2
0
 public async Task <bool> UploadAsync(string targetFile, string sourceFile)
 {
     try
     {
         _ftp = InitailizeFTP(targetFile);
         var fileContent = File.ReadAllBytes(sourceFile);
         _ftp.ContentLength = fileContent.Length;
         var buffLength = 2048;
         var buff       = new byte[buffLength];
         using (var ms = new MemoryStream(fileContent))
         {
             int contenctLength;
             using (var strm = (await _ftp.GetRequestStreamAsync()))
             {
                 contenctLength = ms.Read(buff, 0, buffLength);
                 while (contenctLength > 0)
                 {
                     strm.Write(buff, 0, contenctLength);
                     contenctLength = ms.Read(buff, 0, buffLength);
                 }
             }
         }
         return(true);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message, e);
     }
 }
コード例 #3
0
ファイル: FtpStream.cs プロジェクト: suyeongpark/Suyeong.Core
        async public static Task <string> FtpUploadAsync(byte[] data, string ftpPath, string user, string password)
        {
            string result = string.Empty;

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(requestUriString: ftpPath);
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.Credentials   = new NetworkCredential(userName: user, password: password);
                request.ContentLength = data.Length;

                using (Stream stream = await request.GetRequestStreamAsync())
                {
                    await stream.WriteAsync(buffer : data, offset : 0, count : data.Length);

                    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                    {
                        result = response.StatusDescription;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(result);
        }
コード例 #4
0
        public override async Task Upload(string path, string name, byte[] buffer, bool allowCreateDirectory = true)
        {
            Exception exception         = null;
            bool      directoryNotExist = false;

            try
            {
                if (base.Config.Folder != "/")
                {
                    path = base.Config.Folder + path.TrimStart('/');
                }

                string url = string.Format("{0}://{1}:{2}/{3}/{4}"
                                           , base.Config.Protocol
                                           , base.Config.Server
                                           , base.Config.Port
                                           , path.Trim('/')
                                           , name
                                           );

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
                request.UseBinary     = true;
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.ContentLength = buffer.Length;
                request.Credentials   = new NetworkCredential(base.Config.Username, base.Config.Password);
                Stream requestStream = await request.GetRequestStreamAsync();

                await requestStream.WriteAsync(buffer, 0, buffer.Length);

                requestStream.Close();
                await request.GetResponseAsync();

                return;
            }
            catch (WebException ex)
            {
                exception = ex;
                FtpWebResponse response = ex.Response as FtpWebResponse;
                if (response != null)
                {
                    if (response.StatusCode == FtpStatusCode.ActionNotTakenFilenameNotAllowed)
                    {
                        // directory not exist
                        directoryNotExist = true;
                    }
                }
            }

            if (directoryNotExist && allowCreateDirectory)
            {
                await CreateDir(path);
                await Upload(path, name, buffer);
            }
            else
            {
                throw exception;
            }
        }
コード例 #5
0
ファイル: FTPHelper.cs プロジェクト: jaypiix3/HuB
        /// <summary>
        /// Upload file to ftp server
        /// </summary>
        /// <param name="ftpSite"></param>
        /// <param name="uploadFile"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task UploadFileAsync(Uri ftpSite, string uploadFile, string username, string password)
        {
            int totalBytes = 0;

            Console.WriteLine("Uploading {uploadFile} to {ftpSite.AbsoluteUri}...");

            try
            {
                FileInfo fileInfo = new FileInfo(uploadFile);

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpSite);
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.UseBinary     = true;
                request.ContentLength = fileInfo.Length;

                request.Credentials = new NetworkCredential(username, password);
                byte[] byteBuffer = new byte[4096];

                using (Stream requestStream = await request.GetRequestStreamAsync())
                {
                    using (FileStream fileStream = new FileStream(uploadFile, FileMode.Open, FileAccess.Read,
                                                                  FileShare.Read, 4096, useAsync: true))
                    {
                        int bytesRead = 0;
                        do
                        {
                            bytesRead = await fileStream.ReadAsync(byteBuffer, 0, byteBuffer.Length);

                            if (bytesRead > 0)
                            {
                                totalBytes += bytesRead;
                                Console.WriteLine("Uploaded {totalBytes} Bytes");

                                await requestStream.WriteAsync(byteBuffer, 0, bytesRead);
                            }
                        } while (bytesRead > 0);
                    }
                }

                using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
                {
                    Console.WriteLine(response.StatusDescription);
                }

                Console.WriteLine("Uploaded {uploadFile} to {ftpSite.AbsoluteUri}...");
            }
            catch (WebException e)
            {
                Console.WriteLine("Failed to upload {uploadFile} to {ftpSite.AbsoluteUri}.");
                Console.WriteLine(((FtpWebResponse)e.Response).StatusDescription);
                Console.WriteLine(e);
            }
        }
コード例 #6
0
        //public IAsyncResult BeginRequisition(AsyncCallback callback, object asyncState)
        //{
        //    throw new NotImplementedException();
        //}
        private async Task <bool> SendFileToFTP(MeridianResult meridianResult)
        {
            if ((meridianResult != null) && !string.IsNullOrWhiteSpace(meridianResult.FileName))
            {
                try
                {
                    FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(meridianResult.FtpServerInFolderPath + meridianResult.FileName);
                    ftpRequest.Credentials = new NetworkCredential(meridianResult.FtpUserName, meridianResult.FtpPassword);
                    ftpRequest.Method      = WebRequestMethods.Ftp.UploadFile;
                    ftpRequest.UseBinary   = true;
                    ftpRequest.KeepAlive   = false;
                    ftpRequest.Timeout     = Timeout.Infinite;

                    if (meridianResult.UploadFromLocalPath)
                    {
                        using (StreamReader sourceStream = new StreamReader(meridianResult.LocalFilePath + meridianResult.FileName))
                            meridianResult.Content = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                    }

                    using (Stream requestStream = await ftpRequest.GetRequestStreamAsync())
                    {
                        requestStream.Write(meridianResult.Content, 0, meridianResult.Content.Length);
                        requestStream.Flush();
                    }
                    using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse())
                        if (response.StatusCode == FtpStatusCode.ClosingData)
                        {
                            var prefixToTake = meridianResult.IsSchedule ? MeridianGlobalConstants.XCBL_AWC_FILE_PREFIX : MeridianGlobalConstants.XCBL_AWC_REQUISITION_FILE_PREFIX;
                            // MeridianSystemLibrary.LogTransaction(meridianResult.WebUserName, meridianResult.FtpUserName, (prefixToTake + "- Successfully completed request"), "01.06", string.Format("{0} - Successfully completed request for {1}", prefixToTake, meridianResult.UniqueID), string.Format("Uploaded CSV file: {0} on ftp server successfully for {1}", meridianResult.FileName, meridianResult.UniqueID), meridianResult.FileName, meridianResult.UniqueID, meridianResult.OrderNumber, meridianResult.XmlDocument, "Success");
                            if (meridianResult.IsSchedule && MeridianGlobalConstants.CONFIG_AWC_CALL_SSR_REQUEST.Equals(MeridianGlobalConstants.XCBL_YES_FLAG, StringComparison.OrdinalIgnoreCase))
                            {
                                CommonProcess.SendShippingScheduleResponse1(meridianResult);
                            }
                            return(true);
                        }
                        else
                        {
                            //MeridianSystemLibrary.LogTransaction(meridianResult.WebUserName, meridianResult.FtpUserName, "UploadFileToFtp", "03.08", "Error - While CSV uploading file - Inside TRY block", string.Format("Error - While uploading CSV file: {0} with error - Inside TRY block - ", meridianResult.FileName), meridianResult.FileName, meridianResult.UniqueID, meridianResult.OrderNumber, null, "Error 03.08 - Upload CSV to PBS");
                            return(false);
                        }
                }
                catch (Exception ex)
                {
                    //MeridianSystemLibrary.LogTransaction(meridianResult.WebUserName, meridianResult.FtpUserName, "UploadFileToFtp", "03.08", "Error - While CSV uploading file - Inside CATCH block", string.Format("Error - While uploading CSV file: {0} with error {1} - Inside CATCH block - ", meridianResult.FileName, ex.Message), meridianResult.FileName, meridianResult.UniqueID, meridianResult.OrderNumber, null, "Error 03.08 - Upload CSV to PBS");
                    return(false);
                }
            }
            return(false);
        }
コード例 #7
0
ファイル: EX918.cs プロジェクト: lastingyeh/CsharpCookBook
        public static async Task FtpUploadAsync(Uri ftpSite, string uploadFile)
        {
            Console.WriteLine($"Uploading {uploadFile} to {ftpSite.AbsoluteUri}...");

            try
            {
                FileInfo      fileInfo = new FileInfo(uploadFile);
                FtpWebRequest request  = WebRequest.Create(ftpSite) as FtpWebRequest;
                request.Method = WebRequestMethods.Ftp.UploadFile;

                request.UseBinary     = true;
                request.ContentLength = fileInfo.Length;
                request.Credentials   = new NetworkCredential("anonymous", "*****@*****.**");

                byte[] byteBuffer = new byte[4096];

                using (Stream requestStream = await request.GetRequestStreamAsync())
                {
                    using (FileStream fileStream =
                               new FileStream(uploadFile, FileMode.Open, FileAccess.Read,
                                              FileShare.Read, 4096, useAsync: true))
                    {
                        int bytesRead = 0;
                        do
                        {
                            bytesRead = await fileStream.ReadAsync(byteBuffer, 0, byteBuffer.Length);

                            if (bytesRead > 0)
                            {
                                await requestStream.WriteAsync(byteBuffer, 0, bytesRead);
                            }
                        } while (bytesRead > 0);
                    }
                }

                using (FtpWebResponse response =
                           await request.GetResponseAsync() as FtpWebResponse)
                {
                    Console.WriteLine(response.StatusDescription);
                }
                Console.WriteLine($"Uploaded {uploadFile} to {ftpSite.AbsoluteUri}...");
            }
            catch (WebException e)
            {
                Console.WriteLine($"Failed to upload {uploadFile} to {ftpSite.AbsoluteUri}");
                Console.WriteLine((e.Response as FtpWebResponse)?.StatusDescription);
                Console.WriteLine(e);
            }
        }
コード例 #8
0
ファイル: FTPService.cs プロジェクト: TeamA491/Exogredient
        /// <summary>
        /// The SendAsync function takes a file from the local machine
        /// and tries to send it to a FTP server.
        /// </summary>
        /// <param name="ftpURL">The url of the FTP server.</param>
        /// <param name="ftpFolder">The destination folder in the FTP server. </param>
        /// <param name="sourceDirectory"> The directory in which the desired file is located</param>
        /// <param name="userName"> Crendential for FTP server. </param>
        /// <param name="password"> Credential for FTP server. </param>
        /// <returns>A boolean that confirms if sending was successful.</returns>
        public static async Task <bool> SendAsync(string ftpURL, string ftpFolder, string sourceDirectory, string userName, string password)
        {
            // File to send on local machine.
            string archiveFilePath = sourceDirectory + Constants.SevenZipFileExtension;

            if (!File.Exists(archiveFilePath))
            {
                throw new ArgumentException(Constants.FTPfileNotFound);
            }

            byte[] fileBytes = File.ReadAllBytes(archiveFilePath);

            // Create the FTP request. Set the folder and file name.
            FtpWebRequest request = WebRequest.Create(ftpURL + ftpFolder + Path.GetFileName(archiveFilePath)) as FtpWebRequest;

            request.Method = WebRequestMethods.Ftp.UploadFile;

            // Create a variable for FTP responses.
            FtpWebResponse response;

            // Entering in FTP user credentials.
            request.Credentials = new NetworkCredential(userName, password);

            // Specify additional information about the FTP request.
            request.ContentLength = fileBytes.Length;
            request.UsePassive    = true;
            request.UseBinary     = false;
            request.EnableSsl     = false;
            try
            {
                using (Stream requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false))
                {
                    await requestStream.WriteAsync(fileBytes, 0, fileBytes.Length).ConfigureAwait(false);
                }
            }
            catch (WebException e)
            {
                response = e.Response as FtpWebResponse;
                if (response != null)
                {
                    throw new WebException(Constants.FTPinvalidCredentials);
                }
            }
            return(true);
        }
コード例 #9
0
        private static async Task <MemoryStream> DoAsync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                Stream requestStream = await request.GetRequestStreamAsync();

                await requestBody.CopyToAsync(requestStream);

                requestStream.Close();
            }

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

            await response.GetResponseStream().CopyToAsync(responseBody);

            response.Close();

            return(responseBody);
        }
コード例 #10
0
        /// <summary>
        /// Upload a file to the server
        /// </summary>
        /// Name of the file to Create
        /// <param name="fileName">
        /// </param>
        /// <param name="stream">
        /// File content as stream data
        /// </param>
        /// <returns>
        /// Async Task Wrapper
        /// </returns>
        public async Task UploadFileAsync(string fileName, Stream stream)
        {
            try
            {
                Log.Verbose("Request to Upload file {0} to directory {1}", fileName, RemoteDirectory);
                FtpWebRequest ftpRequest = ConstructFtpRequest(fileName);
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                int    bufferLength = 2048;
                byte[] buffer       = new byte[bufferLength];

                using (Stream uploadStream = await ftpRequest.GetRequestStreamAsync())
                {
                    int contentLength = stream.Read(buffer, 0, bufferLength);

                    while (contentLength != 0)
                    {
                        uploadStream.Write(buffer, 0, contentLength);
                        contentLength = stream.Read(buffer, 0, bufferLength);
                    }
                }
                Log.Verbose("Request to Upload file {0} to directory {1} completed", fileName, RemoteDirectory);
            }
            catch (Exception exception)
            {
                // log and throw
                Log.Error(
                    "Error during Upload operation. " +
                    "Directory : {0} , File {1}, Uri : {2}",
                    exception,
                    RemoteDirectory,
                    fileName,
                    FtpUri);

                throw;
            }
        }
コード例 #11
0
        public async Task UpLoadFileAsync(FtpTransferResult ftpResult)
        {
            byte[]        buffer  = new byte[BUFFER_LENGTH];
            FtpWebRequest request = FtpWebRequest.Create("ftp://" +
                                                         this.Ftp.Host + ":" + this.Ftp.Port + ftpResult.Target) as FtpWebRequest;

            request.Credentials      = new NetworkCredential(this.Ftp.UserName, this.Ftp.Password);
            request.Method           = WebRequestMethods.Ftp.UploadFile;
            request.Timeout          = 10000;
            request.ReadWriteTimeout = 10000;
            using (var stream = await request.GetRequestStreamAsync())
                using (var filestream = new FileStream(ftpResult.Info, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    int readed = 0;
                    while ((readed = await filestream.ReadAsync(buffer, 0, BUFFER_LENGTH)) > 0)
                    {
                        await stream.WriteAsync(buffer, 0, readed);

                        ftpResult.Position += readed;
                        ftpResult.Process   = (double)ftpResult.Position / ftpResult.TotalLength * 100;
                    }
                    await stream.FlushAsync();
                }
        }
コード例 #12
0
 public static Task UploadFileAsync(string filePath)
 {
     return(Task.Run(async() =>
     {
         //this is your code with a few changes
         FtpWebRequest request = (FtpWebRequest)WebRequest.Create(
             string.Format("(secret)/{0}", Path.GetFileName(filePath))
             );
         request.Method = WebRequestMethods.Ftp.UploadFile;
         // This example assumes the FTP site uses anonymous logon.
         request.Credentials = new NetworkCredential("secret", "secret");
         // Copy the contents of the file to the request stream.
         StreamReader sourceStream = new StreamReader(filePath);
         byte[] fileContents = Encoding.UTF8.GetBytes(await sourceStream.ReadToEndAsync());
         sourceStream.Close();
         request.ContentLength = fileContents.Length;
         Stream requestStream = await request.GetRequestStreamAsync();
         requestStream.Write(fileContents, 0, fileContents.Length);
         requestStream.Close();
         FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
         Console.WriteLine("STOCK Upload File Complete, status {0}", response.StatusDescription);
         response.Close();
     }));
 }
コード例 #13
0
        public async Task UploadAsync(string remoteFileName, string localFileName)
        {
            try
            {
                GeneralSettings(remoteFileName, WebRequestMethods.Ftp.UploadFile);

                _ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;

                using (var fileStream = File.OpenRead(localFileName))
                {
                    using (var ftpStream = await _ftpWebRequest.GetRequestStreamAsync())
                    {
                        await fileStream.CopyToAsync(ftpStream);
                    }
                }

                _ftpWebRequest = null;
            }
            catch (Exception e)
            {
                Logger.LogCritical(0, e, e.Message);
                throw;
            }
        }
コード例 #14
0
        public async Task <Boolean> UploadFileAsync(string filePath)
        {
            Uri baseUri = new Uri("ftp://" + _url + ':' + _port + '/');

            NetworkCredential networkCredential = new NetworkCredential();

            networkCredential.UserName = _userName;
            networkCredential.Password = _password;

            X509Certificate2 certificate2 = new X509Certificate2(_path + "\\localhost.pfx", "secret");

            FileStream     fileStream = null;
            FtpWebResponse response   = null;

            try
            {
                Uri           fileNameUri = new Uri(baseUri, _dateTime + "/" + Path.GetFileName(filePath));
                FtpWebRequest request     = (FtpWebRequest)WebRequest.Create(fileNameUri);

                request.Credentials = networkCredential;
                request.ClientCertificates.Add(certificate2);
                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                request.EnableSsl   = _ssl;
                request.KeepAlive   = true;
                request.UsePassive  = String.Equals(_mode, "passive", StringComparison.OrdinalIgnoreCase);
                request.UseBinary   = true;
                request.Method      = WebRequestMethods.Ftp.UploadFile;

                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                request.ContentLength = fileStream.Length;

                Stream requestStream = await request.GetRequestStreamAsync();

                byte[] buffer    = new byte[32768];
                int    readBytes = 0;

                do
                {
                    readBytes = await fileStream.ReadAsync(buffer, 0, buffer.Length);

                    await requestStream.WriteAsync(buffer, 0, readBytes);
                }while (readBytes != 0);

                requestStream.Close();

                response = (FtpWebResponse)await request.GetResponseAsync();

                LogService.LogEvent("FTP Server Response: " + response.StatusDescription);

                if (response.StatusCode == FtpStatusCode.ClosingData)
                {
                    return(true);
                }

                return(false);
            }
            catch (WebException ex)
            {
                response = (FtpWebResponse)ex.Response;
                LogService.LogEvent("Error: FtpService.UploadFileAsync - " + response.StatusDescription);

                return(false);
            }
            catch (Exception ex)
            {
                LogService.LogEvent("Error: FtpService.InitializeFtpAsync - " + ex.Message);
                return(false);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                if (response != null)
                {
                    response.Close();
                }
            }
        }
コード例 #15
0
ファイル: FtpWebRequestTest.cs プロジェクト: dotnet/corefx
        private static async Task<MemoryStream> DoAsync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                Stream requestStream = await request.GetRequestStreamAsync();
                await requestBody.CopyToAsync(requestStream);
                requestStream.Close();
            }

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

            return responseBody;
        }
コード例 #16
0
        public async void UploadAsync(string filename, String directory, String newFileName) //上面的代码实现了从ftp服务器上载文件的功能
        {
            FileInfo fileInf = new FileInfo(filename);

            string uri = "ftp://" + ftpServerIP + "/" + directory + "/" + newFileName;

            if (!await DirectoryIsExistAsync(directory))
            {
                await MakeDirAsync(directory);
            }

            Connect(uri);//连接

            // 默认为true,连接不会被关闭

            // 在一个命令之后被执行

            reqFTP.KeepAlive = false;

            // 指定执行什么命令

            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // 上传文件时通知服务器文件的大小

            reqFTP.ContentLength = fileInf.Length;
            // 缓冲大小设置为kb
            int buffLength = 2048;

            byte[] buff = new byte[buffLength];

            int contentLen;

            // 打开一个文件流(System.IO.FileStream) 去读上传的文件

            FileStream fs = fileInf.OpenRead();

            try
            {
                // 把上传的文件写入流

                Stream strm = await reqFTP.GetRequestStreamAsync();

                // 每次读文件流的kb

                contentLen = fs.Read(buff, 0, buffLength);

                // 流内容没有结束

                while (contentLen != 0)
                {
                    // 把内容从file stream 写入upload stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // 关闭两个流

                strm.Close();

                fs.Close();
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #17
0
        public async void FtpImage()
        {
            //create directory for day/repair code
            MakeFTPDir(Values.gFTPServer, ServerPath, Values.gFTPUser, Values.gFTPPassword);
            //create request for image uploading
            string uri = "ftp://" + Values.gFTPServer + ServerPath + File.Name;
            // Create FtpWebRequest object from the Uri provided
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new System.Uri(uri));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(Values.gFTPUser, Values.gFTPPassword);
            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive  = false;
            reqFTP.UsePassive = true;
            // 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

            long FileLenght = File.Length();

            reqFTP.ContentLength = FileLenght;
            //string transmissions = (this.Count - pendingItems.Count).ToString() + "/" + this.Count.ToString();
            //int pending_old = pendingItems.Count;
            //cParentActivity.RunOnUiThread(() => cTextView.Text = "Upload " + transmissions + ": " + pendingImage.File.Name + "...");
            // The buffer size is set to 2kb
            int buffLength = 1024;

            byte[] buff = new byte[buffLength];
            int    contentLen;
            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileInputStream fs = new FileInputStream(File);

            // Stream to which the file to be upload is written
            try
            {
                System.IO.Stream strm = await reqFTP.GetRequestStreamAsync();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);
                // Till Stream content ends
                int totalRead = 0;
                while (contentLen != -1)
                {
                    totalRead += contentLen;
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                    //Java.Lang.Thread.Sleep(5);
                    //updates the progress bar
                    intProgress = (int)(100 * totalRead / FileLenght);
                    if (null != Progress)
                    {
                        Activity.RunOnUiThread(() => Progress.Progress = intProgress);
                    }
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();
                Uploaded = true;

                string FileName = File.Name;
                byte[] rawBitmap;
                using (var stream = new System.IO.MemoryStream())
                {
                    Bitmap.Compress(Bitmap.CompressFormat.Jpeg, 0, stream);
                    rawBitmap = stream.ToArray();
                }
                Status = "UPLOADED";

                SP pAddPicturesRepairs = new SP(Values.gDatos, "pAddPicturesRepairsNEW");
                pAddPicturesRepairs.AddParameterValue("RepairCode", cRepairCode);
                pAddPicturesRepairs.AddParameterValue("UnitNumber", cUnitNumber);
                pAddPicturesRepairs.AddParameterValue("FileName", FileName);
                pAddPicturesRepairs.AddParameterValue("FilePath", ServerPath);
                pAddPicturesRepairs.AddParameterValue("Thumbnail", rawBitmap);
                pAddPicturesRepairs.AddParameterValue("IdPicture", "");
                pAddPicturesRepairs.AddParameterValue("Num", NumPicture);
                pAddPicturesRepairs.Execute();
                if (pAddPicturesRepairs.LastMsg != "OK")
                {
                    throw (new Exception(pAddPicturesRepairs.LastMsg));
                }

                //delete the local file once transmitted
                IdPicture = pAddPicturesRepairs.Parameters["@IdPicture"].Value.ToString();
                bool deleted = File.Delete();
                File.Dispose();
                File = null;
                return;
            }
            catch (System.Exception ex)
            {
                Activity.RunOnUiThread(() =>
                {
                    Android.App.AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                    AlertDialog alertDialog = builder.Create();
                    alertDialog.SetTitle("ERROR");
                    alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
                    alertDialog.SetMessage("Error: " + ex.Message);
                    alertDialog.SetButton("OK", (s, ev) =>
                    {
                        Activity.Finish();
                    });
                    alertDialog.Show();
                });
                return;
            }
        }
コード例 #18
0
        private async Task <string> InternalUpload(UploadMode mode, Stream stream, CancellationToken cancelToken, ProgressMonitorBase progress, FtpOptions options = null)
        {
            cancelToken.ThrowIfCancellationRequested();
            options = options ?? Handler.Options;
            long size = -1;

            if (progress != null)
            {
                if (progress.AskForSize)
                {
                    try {
                        size = stream.Length;
                    } catch (NotSupportedException) { }
                }
                progress.Progress = new FtpProgress(size);
                progress.OnInit();
            }
            byte[] buffer    = new byte[options.BufferSize];
            int    readCount = 0;
            var    protocol  = string.Empty;

            switch (mode)
            {
            case UploadMode.Upload:
                protocol = WebRequestMethods.Ftp.UploadFile;
                break;

            case UploadMode.UploadAsUnique:
                protocol = WebRequestMethods.Ftp.UploadFileWithUniqueName;
                break;

            case UploadMode.Append:
                protocol = WebRequestMethods.Ftp.AppendFile;
                break;
            }
            ;
            FtpWebRequest request = Handler.MakeRequest(cancelToken, options, Target, protocol);

            if (size != -1)
            {
                request.ContentLength = size;
            }
            using (var requestStream = await request.GetRequestStreamAsync()) {
                cancelToken.ThrowIfCancellationRequested();
                do
                {
                    readCount = await stream.ReadAsync(buffer, 0, options.BufferSize, cancelToken);

                    await requestStream.WriteAsync(buffer, 0, readCount, cancelToken);

                    cancelToken.ThrowIfCancellationRequested();
                    if (progress != null)
                    {
                        progress.Progress.CurrentCount += readCount;
                        progress.Progressed();
                    }
                } while (readCount > 0);
            }
            if (mode == UploadMode.UploadAsUnique)
            {
                using (var response = (FtpWebResponse)await request.GetResponseAsync()) {
                    cancelToken.ThrowIfCancellationRequested();
                    return(Path.GetFileName(response.ResponseUri.ToString()));
                }
            }
            return(null);
        }