void Upload(int TaskID)
        {
            UploadTask Task = (UploadTask)TaskList[TaskID];

            if (TaskList.Count == 1)
            {
                //一次性上传
                Client.UploadFileAsync(new Uri($"https://pcs.baidu.com/rest/2.0/pcs/file?method=upload&path={UploadPath}&access_token={Program.config.Access_Token}"), FilePath);
            }
            else
            {
                //分片上传
                Client.UploadFileAsync(new Uri($"https://pcs.baidu.com/rest/2.0/pcs/file?method=upload&access_token={Program.config.Access_Token}&type=tmpfile"), Task.FilePath);
            }
        }
Example #2
0
        private void SendAsync()
        {
            using (WebClient myWebClient = new WebClient())
            {
                try
                {
                    myWebClient.Credentials = new NetworkCredential(mGitutilCommand.ExternalFTPUser.Normalize(),
                                                                    mGitutilCommand.ExternalFTPPassword.Normalize());

                    myWebClient.UploadFileCompleted   += OnFileUploadCompleted;
                    myWebClient.UploadProgressChanged += OnProgressUpload;

                    myWebClient.UploadFileAsync(new Uri(string.Format(@"ftp://{0}/{1}",
                                                                      mGitutilCommand.ExternalFTPPath,
                                                                      new FileInfo(mGitutilCommand.CreatedZipFile).Name)), "STOR", mZipFileCreated.filePath, Guid.NewGuid().ToString());

                    Uri tmp = new Uri(string.Format(@"ftp://{0}/{1}",
                                                    mGitutilCommand.ExternalFTPPath, new FileInfo(mGitutilCommand.CreatedZipFile).Name));
                }
                catch (Exception e)
                {
                    string error = e.Message;
                }
            }
        }
Example #3
0
        public PictureUpload()
        {
            MainWindow.progressBar.Visibility = Visibility.Visible;
            using (webClient)
            {
                webClient.UploadProgressChanged += WebClient_UploadProgressChanged;
                webClient.UploadFileCompleted   += WebClient_UploadFileCompleted;

                //Check if clipboard data is a bitmapsource
                if (Clipboard.ContainsImage())
                {
                    byte[] imageBytes = Handlers.BitmapSourceToByte(Clipboard.GetImage());

                    try
                    {
                        File.WriteAllBytes(MainWindow.pictureOfflineSource, imageBytes);

                        webClient.UploadFileAsync(new Uri(MainWindow.postURLImageFile), MainWindow.pictureOfflineSource);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Error1");
                    }
                }
                else if (Clipboard.ContainsFileDropList())
                {
                    if (Handlers.ClipBoardContainsDropFileImg())
                    {
                        UploadFilesAsync();
                    }
                }
            }
        }
Example #4
0
 private void uploadAsync()
 {
     try
     {
         using (var client = new WebClient())
         {
             client.UploadProgressChanged += Client_UploadProgressChanged;
             client.UploadFileCompleted   += Client_UploadFileCompleted;
             if (!string.IsNullOrWhiteSpace(ewoObj.pictureLocalPath))
             {
                 Toast.MakeText(Application.ApplicationContext, "Compressing Image...", ToastLength.Short).Show();
                 SelectedFileName = BitmapHelpers.ResizeImage(ewoObj.pictureLocalPath);
                 Toast.MakeText(Application.ApplicationContext, "Uploading Image", ToastLength.Short).Show();
                 client.UploadFileAsync(new System.Uri(serverURL + ":9080/upload"), SelectedFileName);
             }
             else
             {
                 Client_UploadFileCompleted(null, null);
             }
         }
     }
     catch (Exception ex)
     {
         ex.ToString();
         ButtonRow.Visibility = ViewStates.Visible;
         Toast.MakeText(Application.ApplicationContext, "There was an error uploading the image Please contact your manager or developer.", ToastLength.Short).Show();
     }
 }
Example #5
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="url"></param>
 /// <param name="fileName">路径</param>
 /// <param name="progress"></param>
 /// <param name="complete"></param>
 public void UploadFile(string url, string fileName, Action <float, float> progress, Action complete)
 {
     try
     {
         WebClient wc = new WebClient();
         wc.UploadProgressChanged += (sender, arg) =>
         {
             if (progress != null)
             {
                 progress(arg.BytesSent, arg.TotalBytesToSend);
                 if (!download)
                 {
                     wc.CancelAsync();
                     UnityEngine.Debug.LogError("中止上传!");
                 }
             }
         };
         wc.UploadFileCompleted += (sender, arg) =>
         {
             if (complete != null)
             {
                 complete();
             }
         };
         wc.UploadFileAsync(new Uri(url), fileName);
     }
     catch (Exception e)
     {
         UnityEngine.Debug.LogError(e);
     }
 }
Example #6
0
        private void UploadAsync()
        {
            _Client = null;

            if (_uploadList.Any())
            {
                UploadInfo uploadInfo = _uploadList[0];

                _Client             = new WebClient();
                _Client.Credentials = System.Net.CredentialCache.DefaultCredentials;
                _Client.Proxy       = null;

                _Client.UploadProgressChanged += new UploadProgressChangedEventHandler(_Client_UploadProgressChanged);
                _Client.UploadFileCompleted   += new UploadFileCompletedEventHandler(_Client_UploadFileCompleted);

                var url = Login._ServerPath + "upload.php";

                //_Client.UploadFileAsync( new Uri(url), "POST", uploadInfo._filePath, uploadInfo._uploadUrl);
                _Client.UploadFileAsync(new Uri(uploadInfo._uploadUrl), "POST", uploadInfo._filePath, uploadInfo._uploadUrl);
                //_Client.UploadFile(new Uri(uploadInfo._uploadUrl), uploadInfo._filePath);

                //_ProgressBarWindow.Show();
                //_ProgressBarWindow.Left = uploadInfo._window.Left + uploadInfo._window.Width / 2;
                //_ProgressBarWindow.Top = uploadInfo._window.Top + uploadInfo._window.Height / 2;

                return;
            }

            //_ProgressBarWindow.Hide();
        }
Example #7
0
    /// <summary>
    /// Uploads the file.
    /// </summary>
    public static void UploadFile()
    {
        DebugLevelController.Log("Path: " + FilePath, 1);
        DebugLevelController.Log("Username: "******"Pass: "******"Host: ftp://" + FTPHost, 1);

        //end uploading

        /*t2_ = new Thread(UploadThread);
         * if (!t2_.IsAlive)
         *  t2_.Start();*/
        StaticCoroutine.Start(UploadThread());

        EditorLogGenerator.GenerateLog("Upload started");
        shouldCheck = true;

        Uri uri2 = new Uri("ftp://" + FTPHost + "version.thln");

        client2.Credentials          = new System.Net.NetworkCredential(FTPUserName, FTPPassword);
        client2.UploadFileCompleted += new UploadFileCompletedEventHandler(OnFileUploadCompleted2);
        client2.UploadFileAsync(uri2, "STOR", Application.dataPath + "/../TheLauncher/version/version.thln");
        EditorLogGenerator.GenerateLog("Version File Upload Started");

        Uri uri3 = new Uri("ftp://" + FTPHost + "v.thln");

        client3.Credentials          = new System.Net.NetworkCredential(FTPUserName, FTPPassword);
        client3.UploadDataCompleted += new UploadDataCompletedEventHandler(OnFileUploadCompleted3);
        byte[] bytes3 = File.ReadAllBytes(Application.dataPath + "/../TheLauncher/version/v.thln");
        client3.UploadDataAsync(uri3, "STOR", bytes3);
        EditorLogGenerator.GenerateLog("File List Upload Started");
    }
Example #8
0
            public static void Upload(string fileName, UType uType = UType.CurrentFolder)
            {
                /*byte[] response = webClient.UploadFile(
                 *  new Uri(ulUrl+"?uploadTo=" + uploadTo),
                 *  ulDirectory+"/"+fileName
                 * );
                 *
                 * Console.WriteLine(Encoding.ASCII.GetString(response));*/

                //Async
                totalBytes = new FileInfo(ulDirectory + "/" + fileName).Length;
                string curUrl = ulUrl + "?uploadTo=" + uploadTo;

                string[] pathArgs = fileName.Split("/");
                curUrl += "&folder=/" + fileName.Substring(0, fileName.Length - pathArgs[pathArgs.Length - 1].Length - 1);
                Console.WriteLine(curUrl);

                webClient.UploadFileAsync(
                    new Uri(curUrl),
                    ulDirectory + "/" + fileName
                    );

                /*
                 * totalBytes = new FileInfo(ulDirectory + "/" + fileName).Length;
                 * ulUrl = FixUri(ulUrl);
                 * string curUrl = ulUrl + "?uploadTo=" + uploadTo;
                 * string[] pathArgs = fileName.Split("/");
                 * curUrl += "&folder=" + HttpUtility.UrlEncode(fileName.Substring(0, fileName.Length - pathArgs[pathArgs.Length - 1].Length - 1));
                 * webClient.UploadFileAsync(
                 *  new Uri(ulUrl),
                 *  ulDirectory + "/" + fileName
                 * );
                 */
            }
        public void Upload(string url, string fileName, List <KeyValuePair <string, string> > headers)
        {
            WebClient webClient = new WebClient();

            // add event handlers for completed and progress changed
            webClient.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressChanged);
            webClient.UploadFileCompleted   += new UploadFileCompletedEventHandler(UploadFileCompleted);

            webClient.Headers.Add("user-agent", Config.settings.about.product + " " + Config.settings.about.version);
            foreach (KeyValuePair <string, string> header in headers)
            {
                webClient.Headers.Add(header.Key, header.Value);
            }
            Uri uri = new Uri(url);

            string sync = MySerialize.ToJSON(Sync.syncSettings);


            MyLog.Add("Upload to uri:" + uri.ToString() + " sync:" + sync + " file:" + fileName);


            int progress = 0;

            subFormProgressSyncUp.Value(progress);
            subFormProgressSyncUp.Text("Uploading..");

            webClient.UploadFileAsync(uri, fileName);
        }
Example #10
0
        public void scan(string filename)
        {
            WebClient wc = new WebClient {
                Proxy = null
            };
            bool scanned = false;

            wc.UploadFileCompleted += delegate(object sender, UploadFileCompletedEventArgs args) {
                string response = Encoding.UTF8.GetString(args.Result);
                Dictionary <string, string> dict = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(response);
                string url = dict["url"];
                dict.Remove("url");
                dict.Remove("result");
                link    = url;
                Results = dict;
                ScanState("Scan complete.");
                scanned = true;
            };

            if (ScanState != null)
            {
                ScanState("Starting upload...");

                ScanState(string.Format("Attempting to scan file '{0}'.", new FileInfo(filename).Name));
            }

            wc.UploadFileAsync(new Uri("http://www.refud.me/api.php?auth_token=" + token + "&type=text"), "POST", filename);
            while (!scanned)
            {
                Thread.Sleep(300);
            }
        }
        /// <summary>
        /// Attaches a file to the wiki by using an async call.
        /// </summary>
        /// <param name="docName">The full name of the wiki page.</param>
        /// <param name="filePath">The path to the file to be attached.</param>
        public void AddAttachmentAsync(string docName, string filePath)
        {
            String uploadAddress = serverURL + XWikiURLs.AttachmentServiceURL;

            uploadAddress += "&page=" + docName + "&action=attachFile";
            webClient.UploadFileAsync(new Uri(uploadAddress), filePath);
        }
Example #12
0
        public static void UploadFile(string fileName, string serverUrl,
                                      Action <object, UploadFileCompletedEventArgs> completeAction,
                                      Action <object, UploadProgressChangedEventArgs> progressAction
                                      )
        {
            using (var myClient = new WebClient())
            {
                if (completeAction != null)
                {
                    myClient.UploadFileCompleted += completeAction.Invoke;
                }
                if (progressAction != null)
                {
                    myClient.UploadProgressChanged += progressAction.Invoke;
                }

                myClient.UploadFileAsync(new Uri(serverUrl), fileName);
            }

            //using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open), new UTF8Encoding())) // do anything you want, e.g. read it
            //{

            //    // ...
            //}
        }
Example #13
0
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc       = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws <NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws <NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return(Task.CompletedTask);
     });
 }
Example #14
0
        /// <summary>
        ///     Checks if file exists and uploads file. This along with parsing the output of the JSON response.
        /// </summary>
        /// <param name="fileLocation"> The specified path to the file to be uploaded. </param>
        /// <param name="handler"> A progress changed handler that can monitor the progress of the upload. </param>
        public AnonFile UploadFileAsync(string fileLocation, UploadProgressChangedEventHandler handler = null)
        {
            string         response   = null;
            AutoResetEvent waitHandle = new AutoResetEvent(false);

            if (!File.Exists(fileLocation))
            {
                throw new AnonFileException($"Invalid file path at {fileLocation}");
            }

            _client.UploadFileAsync(new Uri("https://api.anonfile.com/upload"), fileLocation);


            if (handler != null)
            {
                _client.UploadProgressChanged += handler;
            }

            _client.UploadFileCompleted += (self, e) =>
            {
                waitHandle.Set();
                response = Encoding.Default.GetString(e.Result);
            };

            waitHandle.WaitOne();
            waitHandle.Dispose();

            return(response != null?ParseOutput(response) : throw new AnonFileException("Failed to grab AnonFile's server response to the upload event!"));;
        }
        private void UploadCatalog(string catalogFilename, string userName, string password)
        {
            if (!this.uploadInProgress)
            {
                return;
            }

            FileInfo fi = new FileInfo(catalogFilename);

            this.Dispatcher.Invoke((Action)(() =>
            {
                progressBar.Maximum = (int)fi.Length;
            }));

            string hostName = "http://" + myHitbaseHostName + "/myhitbase/UploadCatalog.cshtml";

#if DEBUG
//            if (Environment.MachineName == "JUS2")
//                hostName = "http://localhost:9694/UploadCatalog.cshtml";
#endif

            Uri uri = new Uri(hostName);
            webClient.Headers.Add("user", userName);
            webClient.Headers.Add("password", password);
            webClient.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
            webClient.UploadFileCompleted   += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);
            webClient.UploadFileAsync(uri, "POST", catalogFilename);
        }
Example #16
0
        private void UploadFile(String fileNamePath, String uriString)
        {
            SetLoadingLabel("正在上传数据库...");
            try
            {
                //FTPRenameRemoteFile(); // 重命名
                if (!FormBasicFeatrues.GetInstence().FTPRenameRemoteFile(MainWindow.ONLINE_DATABASE_FTP_LOCATION_DIR + MainWindow.ONLINE_DATABASE_FILE_PREFIX, MainWindow.USER_ID + "_backup@" + DateTime.Now.ToString("yyyy-MM-dd&HH-mm-ss") + ".db"))
                {
                    canClose          = true;
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }

                using (WebClient client = new WebClient())
                {
                    Uri uri = new Uri(uriString);
                    client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
                    client.UploadFileCompleted   += new UploadFileCompletedEventHandler(UploadFileCompleteCallback);
                    //DatabaseConnections.Connector.LocalDbClose();
                    client.UploadFileAsync(uri, "STOR", fileNamePath);
                    // client.Proxy = WebRequest.DefaultWebProxy;
                    //client.Proxy.Credentials = new NetworkCredential(ONLINE_FTP_USERNAME, ONLINE_FTP_PASSWORD, ONLINE_FTP_DOMAIN);
                    client.Dispose();
                }
            }
            catch
            {
                SetLoadingLabel("正在上传数据库错误,请在下次登录时重试...");
                canClose          = true;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }
Example #17
0
        /// <summary>
        /// Upload file content asynchron.
        /// Progress is signaled via UploadProgressChanged and UploadFileCompleted event.
        /// </summary>
        /// <param name="fileName">File to upload content</param>
        public void UploadFileEvents(string fileName)
        {
            lock (_syncRootAsync)
            {
                // Abort other operation.
                if (_gettAsync != null)
                {
                    _gettAsync.DownloadDataCompleted   -= Gett_DownloadDataCompleted;
                    _gettAsync.DownloadFileCompleted   -= Gett_DownloadFileCompleted;
                    _gettAsync.DownloadProgressChanged -= Gett_DownloadProgressChanged;
                    _gettAsync.UploadDataCompleted     -= Gett_UploadDataCompleted;
                    _gettAsync.UploadFileCompleted     -= Gett_UploadFileCompleted;
                    _gettAsync.UploadProgressChanged   -= Gett_UploadProgressChanged;

                    if (_gettAsync.IsBusy)
                    {
                        _gettAsync.CancelAsync();
                    }
                }

                // GET request
                _gettAsync = new WebClient();
                _gettAsync.UploadFileCompleted   += Gett_UploadFileCompleted;
                _gettAsync.UploadProgressChanged += Gett_UploadProgressChanged;
                _gettAsync.UploadFileAsync(new Uri(_gettFileInfo.Upload.PostUrl), fileName);
            }
        }
Example #18
0
        private void RemoteInstallBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(InstallerPath))
            {
                return;
            }
            ValidatePackagingMethods(InstallerPath);

            // ToDo: validate installer file

            // Check if online packaging is possible (i.e. account limits)
            if (!string.IsNullOrEmpty(CannotOnlinePackagerReason))
            {
                MessageBox.Show(CannotOnlinePackagerReason);
                return;
            }

            // Submit file
            string args = "";

            if (!string.IsNullOrEmpty(InstallerArgs))
            {
                args = "&args=" + InstallerArgs;
            }
            var url = Server.BuildUrl("RdpCapture", false, "&client=Play.WinTSC");

            url += "&" + Server.AuthUrl();
            var webClient = new WebClient();

            webClient.UploadProgressChanged += UploadProgressChanged;
            webClient.UploadFileCompleted   += SubmitRdpCaptureFileUploadCompleted;
            webClient.UploadFileAsync(new Uri(url), InstallerPath);
            ProgressText("Uploading");
            SetUiMode(UiMode.Working);
        }
Example #19
0
        private static void UploadFile(string filename)
        {
            var wc = new WebClient();

            Console.WriteLine("Uploading replay file: {0}", filename);
            wc.UploadFileAsync(new Uri(UPLOAD_URL), filename);
        }
Example #20
0
 public void UploadFileAsync(Uri uri, string filePath, UploadProgressChangedEventHandler progressHandler = null, UploadFileCompletedEventHandler completedHandler = null)
 {
     lhLoom.RunAsync(() =>
     {
         using (WebClient client = new WebClient())
         {
             client.UploadProgressChanged += (sender, e) => {
                 lhLoom.RunMain(() =>
                 {
                     if (progressHandler != null)
                     {
                         progressHandler(sender, e);
                     }
                 });
             };
             client.UploadFileCompleted += (sender, e) => {
                 lhLoom.RunMain(() =>
                 {
                     if (completedHandler != null)
                     {
                         completedHandler(sender, e);
                     }
                 });
             };
             client.UploadFileAsync(uri, filePath);
         }
     });
 }
Example #21
0
        public override void Run(IUpstream source, params string[] args)
        {
            if (!NetworkManager.Instance.IsSelected)
            {
                return;
            }

            src      = source;
            filename = string.Format("animus{0}.jpg", Guid.NewGuid().ToString("N"));
            Size sz      = Screen.PrimaryScreen.Bounds.Size;
            var  hDesk   = libgdi32.GetDesktopWindow();
            var  hSrce   = libgdi32.GetWindowDC(hDesk);
            var  hDest   = libgdi32.CreateCompatibleDC(hSrce);
            var  hBmp    = libgdi32.CreateCompatibleBitmap(hSrce, sz.Width, sz.Height);
            var  hOldBmp = libgdi32.SelectObject(hDest, hBmp);
            bool b       = libgdi32.BitBlt(hDest, 0, 0, sz.Width, sz.Height, hSrce, 0, 0, (CopyPixelOperation)0x40cc0020);

            using (var bmp = Image.FromHbitmap(hBmp)) {
                libgdi32.SelectObject(hDest, hOldBmp);
                libgdi32.DeleteObject(hBmp);
                libgdi32.DeleteDC(hDest);
                libgdi32.ReleaseDC(hDesk, hSrce);
                bmp.Save(filename, ImageFormat.Jpeg);
            }
            client.Headers.Add("Content-Type", "binary/octet-stream");
            client.UploadFileCompleted += UploadFileCompletedCallback;
            client.UploadFileAsync(new Uri(UPLOAD_URI), "POST", filename);
        }
 void _webClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
 {
     using (DelayedPropertyChanged())
     {
         if (e.Cancelled)
         {
             OnUploadCompleted();
         }
         else
         {
             if (e.Error != null)
             {
                 OnUploadError(e.Error);
             }
             else
             {
                 DoDeleteFile(Files[0]);
                 _progressPercentage = 0;
                 if (Files.Count > 0)
                 {
                     _webClient.UploadFileAsync(_uploadUri, Files[0].FullName);
                 }
                 else
                 {
                     OnUploadCompleted();
                     _success = true;
                 }
             }
         }
     }
 }
Example #23
0
        public void loadVideoSite()
        {
            try
            {
                if (File.Exists(SaveFolder.Text + @"\" + VideoName.Text + ".avi"))
                {
                    WebClient           client     = new WebClient();
                    NameValueCollection parameters = new NameValueCollection();
                    parameters.Add("idI", VideoRecorderZ.Properties.Settings.Default.userId);
                    client.QueryString = parameters;


                    string myFile = SaveFolder.Text + @"\" + VideoName.Text + ".avi";
                    client.Credentials = CredentialCache.DefaultCredentials;
                    client.Headers.Add("Content-Type", "binary/octet-stream");

                    client.UploadFileAsync(new Uri(@"http://videorecorder.ru/api/app/videoSend.php"), "POST", myFile);


                    client.Dispose();
                }
                else
                {
                    MessageBox.Show("Файл не найден!");
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Example #24
0
        /// <summary>Uploads a file to the specified resource, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI to which the file should be uploaded.</param>
        /// <param name="method">The HTTP method that should be used to upload the file.</param>
        /// <param name="fileName">A path to the file to upload.</param>
        /// <returns>A Task containing the data in the response from the upload.</returns>
        public static Task <byte[]> UploadFileTask(this WebClient webClient, Uri address, string method, string fileName)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <byte[]>(address);

            // Setup the callback event handler
            UploadFileCompletedEventHandler handler = null;

            handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => webClient.UploadFileCompleted -= handler);
            webClient.UploadFileCompleted += handler;

            // Start the async work
            try
            {
                webClient.UploadFileAsync(address, method, fileName, tcs);
            }
            catch (Exception exc)
            {
                // If something goes wrong kicking off the async work,
                // unregister the callback and cancel the created task
                webClient.UploadFileCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task that represents the async operation
            return(tcs.Task);
        }
Example #25
0
        private void test_upload_Click(object sender, RoutedEventArgs e)
        {
            WebClient Client = new WebClient();

            Client.UploadFileAsync(new Uri("https://www.bundle-manager.com/up.php"), @"C:\test\b.jar");
            Client.UploadProgressChanged += WebClientUploadProgressChanged;
            Client.UploadFileCompleted   += WebClientCompleted;
        }
Example #26
0
        public void UploadFile()
        {
            WebClient PostWc = new WebClient();

            PostWc.UploadFileAsync(new Uri("http://" + server + ":10086/model/uploadSvfzip"), "post", TempPath + ModelName + ".svfzip");
            PostWc.UploadProgressChanged += PostWc_UploadProgressChanged;
            PostWc.UploadFileCompleted   += PostWc_UploadFileCompleted;
        }
Example #27
0
        private void butnUpload_Click(object sender, EventArgs e)
        {
            WebClient webClient = new WebClient();

            webClient.UploadProgressChanged += WebClientUploadProgressChanged;
            webClient.UploadFileCompleted   += WebClientUploadCompleted;
            webClient.UploadFileAsync(new Uri("http://*****:*****@"C:\Users\wg\Desktop\id\z1.txt");
        }
Example #28
0
        private void UploadImage()
        {
            const string url = "https://gabeazo.com/gabeazo.php";

            var server = new Uri(url);

            _client.UploadFileAsync(server, _filename);
        }
Example #29
0
        /*Once you do this, you can use WebClient almost like normal, except that your URIs start with "ftps://" instead of "ftp://". The one caveat is that you have to specify the method parameter, since there won't be a default one. E.g.*/

        public void upload(Uri uploadUri, string fileName, object state)
        {
            using (var webClient = new WebClient())
            {
                // Note here that the second parameter can't be null.
                webClient.UploadFileAsync(uploadUri, WebRequestMethods.Ftp.UploadFile, fileName, state);
            }
        }
Example #30
0
        public void UploadFile(string chosenFile)
        {
            var client = new WebClient();

            client.UploadFileCompleted   += client_UploadDataCompleted;
            client.UploadProgressChanged += client_UploadDataChanged;
            client.UploadFileAsync(new Uri("https://www.screenshottr.us/upload?uploadAr=file"), "POST", @"" + chosenFile + "");
        }
Example #31
0
        public static void UploadFile_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile(new Uri("http://localhost"), null, null); });

            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null, null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null, null, null); });

            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync(new Uri("http://localhost"), null, null); });
        }
Example #32
0
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return Task.CompletedTask;
     });
 }