/// <summary> ///WebClient uploading files to the server/// </summary> /// <param name= "Filenamepath" >file name, full path format</param> /// <param name= "uristring" >Server folder path</param> Private voidUploadFile (stringFilenamepath,stringuristring) { stringFileName = filenamepath.substring (Filenamepath.lastindexof ("\\") +1); NewFileName= DateTime.Now.ToString ("Yymmddhhmmss") + DateTime.Now.Millisecond.ToString () + filenamepath.substring (Filenamepath.lastindexof (".")); stringFilenameext = filename.substring (Filename.lastindexof (".") +1); if(Uristring.endswith ("/") ==false) uristring = uristring +"/"; Uristring= uristring +NewFileName; ///creating an WebClient instanceWebClient mywebclient =NewWebClient (); Mywebclient.credentials=CredentialCache.DefaultCredentials; //the file to uploadFileStream fs =NewFileStream (FileName, FileMode.Open, FileAccess.Read); //FileStream fs = OpenFile ();BinaryReader r =NewBinaryReader (FS); Try { //You can use the UploadFile method in the following format//Mywebclient.uploadfile (uristring, "PUT", Filenamepath); byte[] Postarray = R.readbytes ((int) fs. Length); Stream Poststream= Mywebclient.openwrite (uristring,"PUT"); if(poststream.canwrite) {poststream.write (Postarray,0, postarray.length); } Else{AppHelper.MessageService.ShowError ("The file is not currently writable! "); } poststream.close (); } Catch{AppHelper.MessageService.ShowError ("File upload failed, please retry ~"); } } /// <summary> ///download server files to client/// </summary> /// <param name= "URL" >downloaded file address, absolute path</param> /// <param name= "Dir" >another directory to store</param> Public voidDownload (stringUrlstringDir) {WebClient Client=NewWebClient (); stringFileName = URL. Substring (URL. LastIndexOf ("\\") +1);//the file name that was downloaded stringPath = Dir+filename;//Save As absolute path + file name Try{WebRequest Myre=WebRequest.Create (URL); } Catch { //MessageBox.Show (exp. Message, "Error"); } Try{client. DownloadFile (Url,filename); FileStream FS=NewFileStream (FileName, FileMode.Open, FileAccess.Read); BinaryReader R=NewBinaryReader (FS); byte[] MByte = R.readbytes ((int) fs. Length); FileStream Fstr=NewFileStream (Path,filemode.openorcreate,fileaccess.write); Fstr. Write (MByte,0,(int) fs. Length); Fstr. Close (); } Catch { //MessageBox.Show (exp. Message, "Error"); } }
C # WinForm File upload download