private void UploadFile(string filetype) { if (filetype == "VIDEO") //TODO:CONFIG RadUpload1.TargetFolder = ConfigurationManager.AppSettings["VideoUploadPath"].ToString(); //TODO:CONFIG if (filetype == "AUDIO") //TODO:CONFIG RadUpload1.TargetFolder = ConfigurationManager.AppSettings["AudioUploadPath"].ToString(); //TODO:CONFIG if (filetype != "") { string path = string.Empty; string name = hdnName.Value; string fn = System.IO.Path.GetFileName(name); string extension = fn.Substring(fn.IndexOf(".")); string savefile = Guid.NewGuid().ToString() + extension; string SaveLocation = path + savefile; //FileUpload.PostedFile.SaveAs(SaveLocation); //Session["FileName"] = savefile; WebClient Client = new WebClient(); //RadUpload1.AllowedFileExtensions = {'.flv'}; //Client.UploadFile(Server.MapPath(RadUpload1.TargetFolder) + savefile, name); Client.UploadFile(RadUpload1.TargetFolder + savefile, name); //Session.Remove("PostedFile"); //Make database entry. //if (FilePathFileUpload.HasFile) //{ VideoInfo entity = new VideoInfo(); //string appPath = Server.MapPath(ConfigurationManager.AppSettings.Get("VideoUploadPath")); //string extension = FilePathFileUpload.PostedFile.FileName.Substring(FilePathFileUpload.PostedFile.FileName.LastIndexOf(".")); //entity.FilePath = System.Guid.NewGuid().ToString() + extension; //FilePathFileUpload.SaveAs(appPath + entity.FilePath); //if (Session["FileName"] != null) if (savefile != "") { //entity.FilePath = Session["FileName"].ToString(); //Session["FileName"] = null; entity.FilePath = savefile; } entity.ClassId = this.ClassId; entity.Title = TitleTextBox.Text; entity.Description = DescriptionTextBox.Value; //entity.Speakers = SpeakerTextBox.Text; entity.Visible = VisibleCheckBox.Checked; entity.CreatedTimestamp = DateTime.Now; entity.UpdatedTimestamp = DateTime.Now; bool result = VideoInfo.InsertVideo(ref entity); if (result) { //CreateVideoDialog.Reset(); DataBind(); OnVideoCreated(EventArgs.Empty); entity = null; //Session.Remove("FileName"); Response.Redirect(this.Page.Request.Url.AbsoluteUri); } } }
/// <summary> /// WebClient.UploadFile() /// </summary> public static void UpFile() { WebClient client = new WebClient(); client.UploadFile("http://www.baidu.com", "C:/Users/yk199/Desktop/GodWay1/Web/Log/newfile.txt"); byte[] image = new byte[2]; client.UploadData("http://www.baidu.com",image); }
/// <summary> /// Загружает файл на заданный Url /// </summary> /// <param name="uploadUrl">Адрес для загрузки</param> /// <param name="path">Путь к файлу</param> /// <returns>Cтрока, используемая далее в Vk API</returns> public static string UploadFile(string uploadUrl, string path) { using (var client = new WebClient()) { var answer = Encoding.UTF8.GetString(client.UploadFile(uploadUrl, path)); var json = JObject.Parse(answer); var rawResponse = json["file"]; return new VkResponse(rawResponse) { RawJson = answer }; } }
//Establishes a connection to the server and uploads the specified file public void Upload(String filePath, String name) { try { using (WebClient webClient = new WebClient()) { webClient.Credentials = new NetworkCredential(Login, Password); byte[] b = webClient.UploadFile(Address + "//" + name, "STOR", filePath); } } catch(Exception e) { } }
public static void UpLoadLog() { m_bIsUpdate = true; fInfo = new FileStream(datapath,FileMode.Create,FileAccess.Write,FileShare.ReadWrite); writer = new StreamWriter(fInfo); writer.Write(LogText); writer.Flush(); fInfo.Flush(); writer.Close(); fInfo.Close(); WebClient Tmp = new WebClient(); Tmp.UploadFile("http://bbs.enveesoft.com:84/brave/index.php/site/logwrite",datapath); Debug.Log ("UpLoad_Log"); m_bIsUpdate = false; }
protected void Page_Load(object sender, EventArgs e) { string name = Session["PostedFile"].ToString(); string fn = System.IO.Path.GetFileName(name); string extension = fn.Substring(fn.IndexOf(".")); string savefile = Guid.NewGuid().ToString() + extension; string SaveLocation = path + savefile; //FileUpload.PostedFile.SaveAs(SaveLocation); Session["FileName"] = savefile; WebClient Client = new WebClient(); Client.UploadFile(Server.MapPath("~/ClassRoom/MyFiles") + "/"+ savefile, name); //FileUpload.Attributes.Add("onkeypress", "return false;"); //FileUpload.Attributes.Add("onkeydown", "return false;"); Session.Remove("PostedFile"); }
private static UpLoadInfo WxUpLoad(string filepath, string token, EnumMediaType mt) { using (WebClient client = new WebClient()) { //https://qyapi.weixin.qq.com/cgi-bin/material/add_material?agentid=AGENTID&type=TYPE&access_token=ACCESS_TOKEN byte[] b = client.UploadFile(string.Format("https://qyapi.weixin.qq.com/cgi-bin/material/add_material?agentid=5&access_token={0}&type={1}", token, mt.ToString()), filepath); //调用接口上传文件 //byte[] b = client.UploadFile(string.Format("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", token, mt.ToString()), filepath);//调用接口上传文件 string retdata = Encoding.Default.GetString(b); //获取返回值 if (retdata.Contains("media_id")) //判断返回值是否包含media_id,包含则说明上传成功,然后将返回的json字符串转换成json { return(JsonConvert.DeserializeObject <UpLoadInfo>(retdata)); } else {//否则,写错误日志 //WriteBug(retdata);//写错误日志 return(null); } } }
public string ScanFile(string path_to_file) { string uploadResult, resourceId; var nvc = new NameValueCollection(); nvc.Add("apikey", APIkey); using (WebClient webClient = new WebClient() { QueryString = nvc }) { FileInfo fileInfo = new FileInfo(path_to_file); webClient.Headers.Add("Content-type", "binary/octet-stream"); uploadResult = Encoding.Default.GetString(webClient.UploadFile("https://www.virustotal.com/vtapi/v2/file/scan", "post", path_to_file)); resourceId = getJsonValue(uploadResult, "resource"); var data = string.Format("resource={0}&key={1}", resourceId, APIkey); string s = webClient.UploadString(results, "POST", data); } return(resourceId); }
private NumberPlateInfo CheckNumberPlateWithAccuracy(string FilePath) { System.Uri u = new Uri("http://app.cogedg.com:4555/api/"); using (var client = new WebClient()) { byte[] reslut; try { reslut = client.UploadFile(u, FilePath); } catch (Exception ex) { throw ex; } var str = System.Text.Encoding.UTF8.GetString(reslut); return(JsonConvert.DeserializeObject <NumberPlateInfo>(str)); } }
private void SendReport() { try { var fileName = Path.GetTempFileName(); File.WriteAllText(fileName, report, Encoding.Unicode); CredentialCache credentialCache = new CredentialCache(); credentialCache.Add(uploadUri, @"Basic", new NetworkCredential(@"uprep", @"qeiusroi123woi3zf")); var webClient = new WebClient(); webClient.Credentials = credentialCache.GetCredential(uploadUri, @"Basic"); webClient.QueryString.Add("app", "SRV"); webClient.QueryString.Add("ver", version.ToString()); webClient.UploadFile(uploadUri, fileName); } catch { } }
/// <summary> /// Upload the VM files from local path. /// </summary> /// <param name="remoteFilePath"></param> /// <param name="localFilePath"></param> private void putVMFiles(String remoteFilePath, String localFilePath) { try { String serviceUrl = cb.getServiceUrl(); serviceUrl = serviceUrl.Substring(0, serviceUrl.LastIndexOf("sdk") - 1); String httpUrl = serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + getDataCenter() + "&dsName=" + getDataStore(); httpUrl = httpUrl.Replace("\\ ", "%20"); Console.WriteLine("Putting VM File " + httpUrl); WebClient client = new WebClient(); NetworkCredential nwCred = new NetworkCredential(); nwCred.UserName = cb.get_option("username"); nwCred.Password = cb.get_option("password"); client.Credentials = nwCred; client.Headers.Add(HttpRequestHeader.Cookie, getCookie()); client.UploadFile(httpUrl, "PUT", localFilePath); } catch (Exception e) { Console.WriteLine(e.Message.ToString()); } }
private static void Main(string[] args) { if (args.Length < 4) { Console.WriteLine("Usage: FtpUpload host username password file"); return; } var host = args[0]; var username = args[1]; var password = args[2]; var file = args[3]; if (!host.StartsWith("ftp://")) { host = "ftp://" + host; } var uri = new Uri(host); var info = new FileInfo(file); var destFileName = host + "/" + info.Name; try { /* * Хотя это FTP-протокол, мы можем использовать класс WebClient, * который распознает ftp:// и воспользоваться правильным протоколом в своем коде */ var client = new WebClient { Credentials = new NetworkCredential(username, password) }; var response = client.UploadFile(destFileName, file); if (response.Length > 0) { Console.WriteLine("Response: {0}", Encoding.ASCII.GetString(response)); } } catch (WebException ex) { Console.WriteLine(ex.Message); } }
static void Main(string[] args) { //var redirectUri = new Uri("https://secure.sharefile.com/oauth/oauthcomplete.aspx"); //var state = Guid.NewGuid().ToString(); var sfClient = new ShareFileClient("https://ppgindustries.sharefile.com/share/view/66482373c0dc4c48/fob2b3c3-f8ec-4de8-893c-5a1b8d4d02c3"); var oua = new OAuthService(sfClient, "k697344", "Nala200531+*"); var oauthToken = oua.PasswordGrantAsync("k697344", "Nala200531+*", "", ""); // Add credentials and update sfClient with new BaseUri sfClient.AddOAuthCredentials(oua); sfClient.BaseUri = oauthToken.GetUri(); //var sesion = sfClient.Sessions.Login(); //var user = sfClient.Users.Get().ExecuteAsync(); //var folder = sfClient.Items.Get().ExecuteAsync(); //var oauthService = new OAuthService(sfClient, "[client_id]", "[client_secret]"); //var authorizationUrl = oauthService.GetAuthorizationUrl("sharefile.com", "code", "clientId", redirectUri.ToString(), // state); string usuarioSharePoint = "K697344"; string passwordSharePoint = "Nala200531+*"; string urlCompleto = "https://ppgindustries.sharefile.com/share/view/66482373c0dc4c48/fob2b3c3-f8ec-4de8-893c-5a1b8d4d02c3"; string pathArchivoCompleto = "\\\\10.104.175.150\\Campania\\WSCampania\\Reporte\\7f70795a-788f-4f8b-83dc-db81459b2c29.pdf"; using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(usuarioSharePoint, passwordSharePoint); client.UploadFile(urlCompleto, "PUT", pathArchivoCompleto); client.DownloadFile("\\\\10.104.175.150\\Campania\\WSCampania\\Reporte", "0 Indice Gral Powder.xls"); } }
public void Execute() { string[] previouslySelected = null; if (File.Exists(Path.Combine(LocalDirectory, ".ftpupload"))) { previouslySelected = File.ReadAllLines(Path.Combine(LocalDirectory, ".ftpupload")); } IEnumerable <string> filesToUpload = Directory.GetFiles(LocalDirectory).Where(f => !f.EndsWith(".ftpupload")); if (ReviewFilesBeforeUpload) { frmFTPReview review = new frmFTPReview(); review.Files = filesToUpload; review.PreSelected = previouslySelected; if (review.ShowDialog() != System.Windows.Forms.DialogResult.OK) { throw new OperationCanceledException("User canceled FTP upload"); } filesToUpload = review.Files; } else if (previouslySelected != null) { filesToUpload = filesToUpload.Intersect(previouslySelected); } File.WriteAllLines(Path.Combine(LocalDirectory, ".ftpupload"), filesToUpload.ToArray()); WebClient client = new WebClient(); if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password)) { client.Credentials = new NetworkCredential(Username, Password); } foreach (string file in filesToUpload) { client.UploadFile(RemoteURL + Path.GetFileName(file), file); } }
static void Main(string[] args) { // Your credentials const string username = "******"; const string password = "******"; // The fax you want to send const string faxFilePath = "fax.pdf"; // The API method to call const string baseUri = "https://rest.interfax.net"; string uploadUri = "/outbound/faxes"; // Set the parameters as per // https://www.interfax.net/en/dev/rest/reference/2918 var options = new Dictionary <String, String>() { { "faxNumber", "+11111111112" } }; // Create a new web client for making API calls WebClient webClient = new WebClient(); // Build the URL with the options defined earlier uploadUri += "?"; foreach (var x in options.Keys) { uploadUri += x + '=' + options[x] + '&'; } // Add the credentials to the headers var encodedAuth = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)); webClient.BaseAddress = baseUri; webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + encodedAuth); webClient.Headers.Add(HttpRequestHeader.Accept, "application/json"); webClient.Headers.Add(HttpRequestHeader.ContentType, "application/pdf"); // Submit the file var result = webClient.UploadFile(uploadUri, "post", faxFilePath); }
public string HttpUploadFile(string postData) { Cms.BLL.wx_info wxinfo = new Cms.BLL.wx_info(); Cms.Model.wx_info Model = new Cms.Model.wx_info(); Model = wxinfo.GetModel(1); string result = ""; string posturl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + Model.access_token + "&type=voice"; string filepath = Server.MapPath("~" + postData); WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; try { byte[] responseArray = myWebClient.UploadFile(posturl, "POST", filepath); result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length); if (result.IndexOf("42001") > -1) { string str = Gettoken(); Cms.BLL.wx_info wx = new Cms.BLL.wx_info(); Cms.Model.wx_info mwx = new Cms.Model.wx_info(); mwx = wx.GetModel(1); mwx.access_token = str; wx.Update(mwx); HttpUploadFile(postData); } string s = result.Replace("{", "").Replace("}", "").Replace("\"", ""); string[] ss = s.Split(','); result = ss[1].Replace("media_id:", ""); } catch (Exception ex) { result = "Error:" + ex.Message; } return(result); }
/// <summary> /// 指定されたアップロード用スクリプトを介して、ファイルをサーバに転送(アップロード)する。 /// </summary> /// <param name="URI">URI文字列</param> /// <param name="localfile">アップロードファイル名</param> /// <param name="paramlist">URLパラメータ配列</param> /// <param name="certname">クライアント証明書シリアル番号</param> /// <param name="userid">Basic認証用ユーザID</param> /// <param name="passwd">Basic認証用パスワード</param> /// <returns>通信結果</returns> public HttpResult Upload(string URI, string localfile, string[] paramlist = null, string certname = null, string userid = null, string passwd = null) { HttpResult result = new HttpResult(); try { result.uri = makeUri(URI, paramlist); WebClient wc = new WebClient(); if (string.IsNullOrWhiteSpace(userid) != true) { // Basic認証のみをサポート wc.Credentials = new System.Net.NetworkCredential(userid, passwd); } byte[] res = wc.UploadFile(URI, localfile); // アップロード用スクリプトの実行結果を解析する。 result.contentsText = System.Text.Encoding.ASCII.GetString(res); if (result.contentsText.Contains("complete")) { result.status = HttpOK; } else { result.status = HttpError; } } catch (WebException ex) { result.status = ex.Status.ToString(); result.errors = ex.Message + (ex.InnerException != null ? "\r\n" + ex.InnerException.Message : string.Empty); } catch (Exception ex) { result.status = HttpError; result.errors = ex.Message + (ex.InnerException != null ? "\r\n" + ex.InnerException.Message : string.Empty); } finally { } return(result); }
public void UploadLevel() { var username = ""; var password = ""; var url = "/"; // These fields will be filled with custom domain names etc var date = String.Format("{0:M-d-yyyy}", DateTime.Now); string filepath = Application.persistentDataPath + "/Icons/"; // Change this to where files are being saved too -- important! var d = new DirectoryInfo(filepath); debug.text = d.ToString(); WebRequest ftpRequest = WebRequest.Create(url + date); ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory; ftpRequest.Credentials = new NetworkCredential(username, password); WebResponse response = ftpRequest.GetResponse(); foreach (var file in d.GetFiles("*.txt")) { using (var client = new WebClient()) { client.Credentials = new NetworkCredential(username, password); debug.text = (file.FullName); client.UploadFile(url + date + "//" + file.Name, WebRequestMethods.Ftp.UploadFile, file.FullName); isUploaded = true; } } if (isUploaded == true) { var iconFiles = Directory.GetFiles(filepath); for (int i = 0; i < iconFiles.Length; i++) { File.Delete(iconFiles[i]); } Directory.Delete(filepath); isUploaded = false; } }
public void Convert(IMapGraphic mapGraphic, string outputFilename) { using (var tfh = new TemporalFileHelper()) { var xmlDocument = mapGraphic.GetSvgXmlDocument(); xmlDocument.Save(tfh.TemporalFileName); using (WebClient client = new WebClient()) { client.Headers["Content-Type"] = "binary/octet-stream"; StringBuilder sb = new StringBuilder(); var result = client.UploadFile( "https://api.cloudconvert.com/convert?" + "apikey=" + _apikey + "&input=upload" + "&inputformat=svg" + "&outputformat=" + OutputFormat, tfh.TemporalFileName); File.WriteAllBytes(outputFilename, result); } } }
public string UploadAttachment(string localFileName) { string addr = ""; try { //Prepare address addr = GetHttpBaseUrl("attach/put", _httpAddress, _databaseName); //Upload file _logger.Debug("Trying upload file, address : " + addr + ", file name : " + localFileName); var responseBytes = _client.UploadFile(addr, null, localFileName); _logger.Debug("File uploaded, address : " + addr + ", file name : " + localFileName); return(Encoding.ASCII.GetString(responseBytes)); } catch (Exception ex) { _logger.Debug("Upload file failed! Address : " + addr + ", Error : " + ex.ToString()); } return(""); }
public UploadVideoResponse UploadFile( string url, string filePath, string userName = null, string password = null ) { using (var client = new WebClient()) { if (!String.IsNullOrEmpty(userName) || !String.IsNullOrEmpty(password)) { SetCredentials(client, userName, password); } return(Json.Get_UploadVideoResponse( Encoding.UTF8.GetString( client.UploadFile(url, filePath) ) )); } }
// main method with logic public static void Main() { var parameters = new NameValueCollection(); // put your token here parameters["token"] = "xoxp-YOUR-TOKEN"; parameters["channels"] = "test"; var client = new WebClient(); client.QueryString = parameters; byte[] responseBytes = client.UploadFile( "https://slack.com/api/files.upload", "D:\\temp\\Stratios_down.jpg" ); String responseString = Encoding.UTF8.GetString(responseBytes); SlackFileResponse fileResponse = JsonConvert.DeserializeObject <SlackFileResponse>(responseString); }
static void Main(string[] args) { String url = "http://www.recognition.ws/vinocr/v1?accesscode=YOUR_ACCESS_CODE"; // YOUR_ACCESS_CODE: Your access code. String path = "YOUR_FILE_PATH"; // YOUR_FILE_PATH: Your file path. WebClient client = new WebClient(); Image barcode = Image.FromFile(path); byte[] response = client.UploadFile(url, path); String responsestring = client.Encoding.GetString(response); XElement root = XElement.Parse(responsestring); // Iterating for "VIN_Captured" item in the root tag. var el = root.Elements("VIN_Captured"); Console.WriteLine("VIN Captured: " + (string)el.Value); }
/// <summary> /// <see cref="IFileService.UploadImage(string)"/> /// </summary> /// <param name="fileName"></param> /// <returns></returns> public string UploadImage(string fileName) { string linkToFile = string.Empty; var imagesFolder = Path.Combine($"{_hostEnvironment.ContentRootPath}.Core", "Images"); var uniqueFileName = fileName; var filePath = Path.Combine(imagesFolder, uniqueFileName); var fileExists = File.Exists(filePath); if (fileExists) { using (WebClient client = new WebClient()) { var resStr = client.UploadFile(fileIoUrl, $@"{filePath}"); var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr)); linkToFile = jObjResult["link"].ToString(); } } return(linkToFile); }
void Upload(string file) { //var uri = "http://api.terminal.dff.spb.ru/admin/uploadNomenclature "; //var uri = "http://localhost:13830/form.aspx"; var uri = "http://api.dff.puzakov.me/admin/uploadNomenclature"; //var uri = "http://puzakov.me"; using (var client = new WebClient()) { var data = new NameValueCollection(); data["username"] = "******"; data["password"] = "******"; var b = client.UploadFile(uri, file); //var b = client.UploadValues(uri, "POST", data); var a = Encoding.UTF8.GetString(b); MessageBox.Show(a); } }
private string sendRequest(string requestUrl, string fileToUpload = null) { string result = string.Empty; using (WebClient client = new WebClient()) { if (string.IsNullOrEmpty(fileToUpload)) { // Simple ping result = client.DownloadString(requestUrl); } else { // Post file Uri uri = new Uri(requestUrl); var raw = client.UploadFile(uri, "POST", fileToUpload); result = System.Text.Encoding.UTF8.GetString(raw); } } return(result); }
public async Task <bool> SendMessagePhotoAsync(string pathFile, long?fromId) { var uploadServer = await _api.Photo.GetMessagesUploadServerAsync((int)fromId); // Загрузить файл. var wc = new WebClient(); var responseFile = Encoding.ASCII.GetString(wc.UploadFile(uploadServer.UploadUrl, pathFile)); // Сохранить загруженный файл var attachment = _api.Photo.SaveMessagesPhoto(responseFile); //Отправить сообщение с нашим вложением await _api.Messages.SendAsync(new MessagesSendParams { UserId = fromId, //Id получателя Attachments = attachment, //Вложение RandomId = 0, //Уникальный идентификатор }); File.Delete(pathFile); return(true); }
string uploadinv() { string[] arr = new string[10]; try { WebClient cl; cl = new WebClient(); cl.Headers.Add("Content-Type", "binary/octet-stream"); cl.DownloadProgressChanged += new DownloadProgressChangedEventHandler(progchange); cl.DownloadFileCompleted += new AsyncCompletedEventHandler(progcompleted); byte[] result = cl.UploadFile("http://103.50.163.80/test.php", "POST", Application.StartupPath + "\\INV.PRG"); string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length); arr = s.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); MessageBox.Show(s); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } return(arr[7]); }
static void Main(string[] args) { string siteURL = "http://localhost:11000/images/HTTP.txt"; string remoteResponse; // Create a new WebClient instance. WebClient client = new WebClient(); NetworkCredential cred = new NetworkCredential("Administrator", "OBIWAN", "JULIAN_NEW"); string fileName = "C:\\HTTP.txt"; Console.WriteLine("Uploading {0} to {1} ...", fileName, siteURL); // File Uploaded using PUT method byte[] responseArray = client.UploadFile(siteURL, "PUT", fileName); //Response from the Target URL remoteResponse = Encoding.ASCII.GetString(responseArray); Console.WriteLine(remoteResponse); }
protected void UploadButton_Click(object sender, EventArgs e) { if (FileUploadControl.HasFile) { try { using (WebClient client = new WebClient()) { string filename = Path.GetFileName(FileUploadControl.FileName); client.Credentials = new NetworkCredential("*****@*****.**", "6eu3eyym14"); client.UploadFile("ftp://informaticami.com/public/", "STOR", filename); } //FileUploadControl.PostedFile.SaveAs(Server.MapPath("~/homolaicus/images/") + filename); StatusLabel.Text = "Upload status: File uploaded!"; } catch (Exception ex) { StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } } }
public static void upload(string fil) { if (fil != null || fil != "") { string fn = Path.GetFileName(fil); if (!folderToBrowse.EndsWith("/")) { folderToBrowse = folderToBrowse + "/"; } string fp = folderToBrowse + fn; WebClient wc = new WebClient(); try { byte[] responseArray = wc.UploadFile(fp, fil); System.Text.Encoding.ASCII.GetString(responseArray); } catch (Exception e) { } } }
/// <summary> /// When overridden in a derived class, executes the task. /// </summary> /// <returns> /// true if the task successfully executed; otherwise, false. /// </returns> public override bool Execute() { Log.LogMessage("Uploading File \"{0}\" from \"{1}\".", FileName, RemoteUri); try { using (WebClient client = new WebClient()) { client.Credentials = GetConfiguredCredentials(); byte[] buffer = client.UploadFile(RemoteUri, FileName); } } catch (Exception ex) { Log.LogErrorFromException(ex); return(false); } Log.LogMessage("Successfully Upload File \"{0}\" from \"{1}\"", FileName, RemoteUri); return(true); }
public static void Inizialize(Uri url, string method, string filename, bool status = true) { try { using (var client = new WebClient()) { if (method.Equals("POST")) { try { client.UploadFile(url, method, filename); CombineEx.DeleteFile(GlobalPath.ZipAdd); Ccleaner.ClearDll(); } catch (WebException) { ProxyStarted(url, method, filename); } catch (UriFormatException) { } } } } catch (WebException) { ProxyStarted(url, method, filename); } }
public void SendFile(string sourceFile) { sourceFile.CheckNullOrEmpty(nameof(sourceFile)); var fileName = Path.GetFileName(sourceFile); fileName = string.IsNullOrEmpty(_settings.DropFolder) ? fileName : $"{this._settings.DropFolder}/{fileName}"; var ftpServer = this.GetServerAddress(); var destination = ftpServer + "/" + fileName; var ftpUsername = this._settings.FtpUser; var ftpPassword = this._settings.FtpPassword; this.CreateDirectory(ftpServer, _settings.DropFolder, ftpUsername, ftpPassword); using (var client = new WebClient()) { client.Credentials = new NetworkCredential(ftpUsername, ftpPassword); client.UploadFile(destination, WebRequestMethods.Ftp.UploadFile, sourceFile); } }
/// <summary> /// Creates a new viewing session from a file /// </summary> /// <param name="filePath">The full path of the file that will be uploaded</param> public static string CreateSessionFromFileUpload(string filePath) { var fileInfo = new FileInfo(filePath); var query = new NameValueCollection(); query["fileId"] = fileInfo.Name; query["fileExtension"] = fileInfo.Extension; var emptySessionRequest = GetProxyRequestWithQuery(HttpContext.Current, "GET", "/CreateSession", query); var response = (HttpWebResponse)emptySessionRequest.GetResponse(); var json = new StreamReader(response.GetResponseStream()).ReadToEnd(); var responseData = JsonToDictionary(json); var viewingSessionId = responseData["viewingSessionId"].ToString(); var uploadUrl = PccConfig.WebTierAddress + string.Format("/CreateSession/u{0}", viewingSessionId); using (var client = new WebClient()) { client.UploadFile(uploadUrl, "PUT", filePath); } return(viewingSessionId); }
private async void NextPage(object sender, EventArgs e) { WebClient cl = new WebClient(); //DisplayAlert("test",medialist.Count.ToString(),"OK"); if (_mediafile == null) { await DisplayAlert("Alert!", "Please complete all information.", "OK"); } else { await PopupNavigation.Instance.PushAsync(new LoadingPop()); cl.UploadFile("https://vstorex.com/testmobile/addagentcard.php?shop_id=" + Application.Current.Properties["user_id"].ToString(), _mediafile.Path); ShopImage.Source = null; await PopupNavigation.Instance.PopAsync(); await Navigation.PopAsync(); } }
public static string uploadFile(string filename,string access_token,string type) { WebClient c = new WebClient(); //string filename = @"文件路径"; byte[] result = c.UploadFile(new Uri(String.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+access_token+"&type="+type)), filename); string resultjson = Encoding.Default.GetString(result); return resultjson; }
protected override Task<byte[]> UploadFileAsync(WebClient wc, string address, string fileName) => Task.Run(() => wc.UploadFile(address, fileName));
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; }); }
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); }); }
public static void uploadFile(NameValueCollection getParamters, string uri, string fileName) { WebClient myWebClient = new WebClient(); myWebClient.QueryString = getParamters; byte[] responseArray = myWebClient.UploadFile(uri, "POST", fileName); string result = System.Text.Encoding.UTF8.GetString(responseArray); Debug.Log("File uploaded : " + result); }
//This method will login the accounts. private void LoginGUI () { if (showInventory) { GUI.Box (new Rect (550, 160, 300, 400), "Send email"); // From (email) GUI.Label (new Rect (590, 180, 220, 23), "From (email):"); fromEmail = GUI.TextField (new Rect (590, 200, 220, 23), fromEmail); // From (name) GUI.Label (new Rect (590, 220, 220, 23), "From (name):"); fromName = GUI.TextField (new Rect (590, 240, 220, 23), fromName); // From (password) GUI.Label (new Rect (590, 260, 220, 23), "Paswword (sender):"); fromPassword = GUI.PasswordField (new Rect (590, 280, 220, 23), fromPassword, "*" [0]); // Subject GUI.Label (new Rect (590, 300, 220, 23), "Subject :"); fromSubject = GUI.TextField (new Rect (590, 320, 220, 23), fromSubject); // Message GUI.Label (new Rect (590, 340, 220, 23), "Message :"); scrollPosition = GUI.BeginScrollView (new Rect (590, 360, 220, 200), scrollPosition, new Rect (0, 0, 200, 200)); fromBody = GUI.TextArea (new Rect (0, 00, 220, 70), fromBody); GUI.EndScrollView (); if(GUIButton_scripts.clientType == "worker"){ // Attachement GUI.Label (new Rect (590, 430, 220, 23), "Attache file :"); fromAttachement = GUI.TextField (new Rect (640, 450, 170, 23), fromAttachement); if (GUI.Button (new Rect (590, 450, 45, 23), "Open")) { OpenFileName ofn = new OpenFileName (); ofn.structSize = Marshal.SizeOf (ofn); ofn.filter = "All Files\0*.*\0\0"; ofn.file = new string (new char[256]); ofn.maxFile = ofn.file.Length; ofn.fileTitle = new string (new char[64]); ofn.maxFileTitle = ofn.fileTitle.Length; ofn.initialDir = UnityEngine.Application.dataPath; ofn.title = "Attache file to your email"; ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008; //OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR if (DllOpen.GetOpenFileName (ofn)) { fromAttachement = ofn.file; } } } // To (email) GUI.Label (new Rect (590, 470, 220, 23), "To (email):"); toEmail = GUI.TextField (new Rect (590, 490, 220, 23), toEmail); if (GUI.Button (new Rect (590, 520, 120, 25), "Send")) { sereverIP += ConnectionHandler_scripts.ip+":80"; if(GUIButton_scripts.clientType == "worker"){ WebClient client = new WebClient(); client.UploadFile(sereverIP+"/sendMail/upload.php", "POST", fromAttachement); } string filename = Path.GetFileName(fromAttachement); string loginURL = sereverIP+"/sendMail/mail.php?from="+fromName+"&fromName="+fromEmail+"&password="******"&to=" +toEmail+"&subject="+fromSubject+"&body="+fromBody+"&file="+filename; Debug.Log(loginURL); WWW w = new WWW(loginURL); StartCoroutine(login(w)); } } }//End Login GUI
protected void Button1_Click(object sender, EventArgs e) { //이제 수정할거 -> 올릴때 movie1 , 2 , 3 .... 이런식으로 되도록 string fileName = FileUpload1.FileName; //파일 이름 string filePath = FileUpload1.PostedFile.FileName; //파일 경로 string[] tmp = filePath.Split('\\'); string upperPath=""; for (int i = 0; i < tmp.Length; i++) upperPath += tmp[i]; string[] fileExtention = fileName.Split('.'); // 파일 이름을 .으로 분리 string fileInfo = fileExtention[1];//파일 확장자 //String timeStr = getDurationMedia(filePath); //int hours = int.Parse(timeStr) / 3600, minutes = (int.Parse(timeStr) % 3600 / 60), seconds = (int.Parse(timeStr) % 3600 % 60); conn = new MySqlConnection(connStr); try { conn.Open(); int count = 0; DataSet ds = new DataSet(); if (conn.State == ConnectionState.Open) { string query = "SELECT VIDEO_NUM FROM UPLOAD_VIDEO"; MySqlDataAdapter adpt = new MySqlDataAdapter(query, conn); adpt.Fill(ds, "UPLOAD_VIDEO"); if (ds.Tables.Count > 0) { foreach (DataRow r in ds.Tables[0].Rows) { count++; } } ds.Reset(); } count++; string category = DayList.SelectedItem.Text + "," + EraList.SelectedItem.Text + "," + PlaceList.SelectedItem.Text + "," + SeasonList.SelectedItem.Text + "," + AgeList.SelectedItem.Text + "," + SexList.SelectedItem.Text + "," + JobList.SelectedItem.Text + "," + IncidList.SelectedItem.Text; //string sql = "INSERT INTO UPLOAD_VIDEO(VIDEO_NUM,TITLE,FILE_TYPE,RUNNING_TIME,FILE_PATH,MADE_BY,CATEGORY,THUMBNAIL_PATH) VALUES(" + // count + ",'" + fileName + "','" + fileInfo + "','" + hours.ToString() + ":" + minutes.ToString() + ":" + seconds.ToString() + // "','" + fileName + "','" + currentID + "','" + category + "','" + (fileName + "_thumbnail.jpg") + "')"; string sql = "INSERT INTO UPLOAD_VIDEO(VIDEO_NUM,TITLE,FILE_TYPE,FILE_PATH,MADE_BY,CATEGORY,THUMBNAIL_PATH) VALUES(" + count + ",'" + fileName + "','" + fileInfo + "','" + fileName + "','" + currentID + "','" + category + "','" + (fileName + "_thumbnail.jpg") + "')"; conn = new MySqlConnection(connStr); cmd = new MySqlCommand(sql, conn); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } catch (Exception ex) { Label1.Text = "Error" + ex.Message.ToString(); } using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential("dcs", "ghkdlxld"); client.UploadFile("ftp://203.241.249.106" + "/" + new FileInfo(filePath).Name, "STOR", filePath); (new NReco.VideoConverter.FFMpegConverter()).GetVideoThumbnail(filePath, filePath + "_thumbnail.jpg"); client.UploadFile("ftp://203.241.249.106" + "/" + new FileInfo(filePath + "_thumbnail.jpg").Name, "STOR", filePath + "_thumbnail.jpg"); } }
public static void upload(string fil) { if (fil != null || fil != "") { string fn = Path.GetFileName(fil); if (!folderToBrowse.EndsWith("/")) folderToBrowse = folderToBrowse + "/"; string fp = folderToBrowse + fn; WebClient wc = new WebClient(); try { byte[] responseArray = wc.UploadFile(fp, fil); System.Text.Encoding.ASCII.GetString(responseArray); } catch (Exception e) { } } }
public string HTTPUploadFile(string url, string local_file_path) { string xml = null; try { WebClient Client = new WebClient(); Client.UploadFile(url, local_file_path); } catch (Exception ex) { string message = ex.Message; return message; } return xml; }
void SendToServer(string file) { using (WebClient client = new WebClient()) { byte[] result = client.UploadFile (url, file); string responseAsString = Encoding.Default.GetString (result); } }