The problem is often encountered in development: the need to download server-side files to the client. There are two kinds of situations, one is the Windows environment and one is the Web environment. Two days ago in the development of WinForm encountered such a problem, the Internet search did not find ready-made demo, so they spent a little time, did a simple file save demo, share the following:
You first need to write a download method that abstracts it into a static class for easy invocation, as follows:
Public Static classFilehelper {/// <summary> ///download server files to client, Create by Wangjianhui/// </summary> /// <param name= "URL" >downloaded file address, absolute path</param> /// <param name= "Dirfilepath" >another directory to store</param> Public Static voidDownloadfiletolocal (stringUrlstringDirfilepath, out stringerrormeesage) {WebClient Client=NewWebClient (); stringFileName = URL. Substring (URL. LastIndexOf ("\\") +1);//the file name that was downloaded//string Path = Dir + fileName; //Save As absolute path + file name Try{WebRequest Myre=WebRequest.Create (URL); Errormeesage=String.Empty; } Catch(Exception E1) {Errormeesage=E1. Message; //MessageBox.Show (E1. Message, "Error"); } Try{client. DownloadFile (URL, Dirfilepath); Errormeesage=String.Empty; } Catch(Exception E2) {Errormeesage=E2. Message; //MessageBox.Show (E2. Message, "Error"); } } }
Now encountered a difficult point is that the saved path can not be written dead, but by the customer's own designation, it is natural to think of the SaveFileDialog control, in the form form to add a SaveFileDialog control, the code to save the button is as follows:
Private voidBtnsave_click (Objectsender, EventArgs e) { stringsourcefile="e:\\filefolder\\123.fff"; System.IO.FileInfo F=NewSystem.IO.FileInfo (sourcefile); stringsourceFileName = F.name;//Original file name stringDirfilepath =string. Empty; Savefiledialogforfff.filename=sourceFileName; Savefiledialogforfff.filter="ebook files (. FFF) |*.fff"; if(Savefiledialogforfff.showdialog () = =DialogResult.OK) {Dirfilepath=Savefiledialogforfff.filename; } stringErrorMessage =string. Empty; Filehelper.downloadfiletolocal (SourceFile, Dirfilepath, outerrormessage); if(!string. IsNullOrEmpty (errormessage)) {MessageBox.Show (errormessage); } Else{MessageBox.Show ("The file has been saved successfully"); } }
When the SaveFileDialog control is opened, the File name text box defaults to the original file name, can also be manually rewritten to other names, through the guide to select the path to save, click the OK button, the server side of the file will be saved to the corresponding path of the client!