C # File upload download function for file Management engine development

Source: Internet
Author: User

Prepare

This article will use a NuGet exposed component technology to implement a server-side file management engine that provides a few simple APIs to facilitate the implementation of the file engine to manage the files of your own software system.

You can download the installation in the NuGet Manager in Visual Studio, or you can enter the following instructions directly in the NuGet console to install:

Install-package hslcommunication

NuGet Installation Tutorial Http://www.cnblogs.com/dathlin/p/7705014.html

QQ Group of Technical Support: 592132877 (the component version update details will be released in the group in the first time)

Summary

The function of this file management engine is to manage the file information uploaded by all clients, and the client will allow the progress report when uploading or downloading. If we just show a file sent to the server, the server will be saved to the local after receiving the data, then this is very easy to implement, as long as the more familiar with network communication can be, but for the file server engine need more logic, allow to upload additional information, including the file uploader, upload date, The number of downloads and so on, and then allow the upload without affecting the download, you can download at the same time, upload, and the server's hard disk IO does not block, so it is very difficult to implement, but all of the above features in the use of this component implementation is very convenient, When the client uploads the download, it is called a method to complete.

This file engine is characterized by the realization of a file read/write separation, no lock read and write, that is, a file content support simultaneous download, upload, and even download, upload, the original download will not be affected. All uploads, downloads, and deletions are thread-safe, regardless of which thread is convenient to call.

Requirements Scenario:

    • For example, we want to develop a project management system, if we want to implement each project allows uploading attachments, need to support convenient download, delete, upload operation.
    • For example, we develop a device data management system, in addition to the device some of the self-contained properties need to create a relational data table, but also support attachment management.
    • For example, we need to implement a software shared File Manager, on the homepage of your software to support convenient display.
    • such as personal account attachment management, profile picture management and so on.

A basic template project based on the expanded CS architecture of this component, two times based on this convenient two development, the project uses several files management:

Https://github.com/dathlin/ClientServerProject

A c-s template, the template is composed of three parts of the program, a server running program, a client run the program, there is a public component, the implementation of the basic account management functions, version control, software upgrades, Bulletin management, message mass, shared file upload download, batch file transfer function. The specific method of operation can be seen in the demo. One goal of this project is to provide a basic c-s framework for small and medium-sized systems, with clients having four modes, seamless integrated access, WinForm version, WPF version, ASP. NET MVC version, and Android version. It facilitates two development and individual learning of small and medium-sized systems in enterprises.

Reference

All of the feature classes in the log component are in the hslcommunication and hslcommunication.enthernet namespaces, so add them before use

Using hslcommunication;using hslcommunication.enthernet;
How to use

First of all, the server-side to build services, basically only need two parameters, port number and the base path of the file engine. As for the log, you can not, to see their own needs, the system will download files, upload, abnormal situation record.

We first on the server code, assuming the need for logging, if you do not need to comment out the two lines of log-related code, the system can also achieve the specified classification of the number of files to monitor, when the number of changes in the time of the update push and so on. OK, let's take a look at one of the simplest ways.

        Private Ultimatefileserver ultimatefileserver;                                            Engine Object        private void Ultimatefileserverinitialization ()        {            ultimatefileserver = new Ultimatefileserver ();                                        Instantiate object            Ultimatefileserver.filesdirectorypath = Application.startuppath + @ "\ultimatefile";   The base path for all file storage            Ultimatefileserver.serverstart (34567);                                                Start a port engine        }                private void Userbutton1_click (object sender, EventArgs e)        {            //clicked Start server-side file engine            ultimatefileserverinitialization ();            userbutton1.enabled = false;        }

Declare a server-side object, then write an initialization method to instantiate the data, and then invoke the initialization method in a button. There are only so many simple versions of the program on the server side.

Client actions: Instantiation:

Client in the file upload, before downloading the client instantiation, when the instantiation can specify some information, currently testing, do not need.

        #region Client Core engine        private integrationfileclient integrationfileclient;                 Client core engine        private void integrationfileclientinitialization ()        {            //define some properties of the connection server, time-out, IP and port information            Integrationfileclient = new Integrationfileclient ()            {                connecttimeout =,                serveripendpoint = new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("127.0.0.1"), 34567),            };            Create a path to the local file store            string path = Application.startuppath + @ "\files";            if (! System.IO.Directory.Exists (path))            {                System.IO.Directory.CreateDirectory (path);            }        }        #endregion

Upload file:

Before explaining the upload file operation, the following document management engine mechanism, for each file, there are three classification mechanism for the classification of files, as well as the label on the server side of the file storage path. When you confirm the upload of a file, you need to confirm that 3 categories and files on the server side of the file name is really stored, usually the name of the file itself. Next, let's upload a file, which comes from a manual selection:

        #region Uploading file blocks/******************************************************************************************** * * An instruction to complete the upload of files, there are three types of upload mode * 1. Specifies the file name of the local full path * 2. Upload data from stream to server * 3. Uploading bitmap picture data to the server * ************************************************************************************* /private void Userbutton3_click (object sender, EventArgs e) {//Click after file selection usi Ng (OpenFileDialog ofd = new OpenFileDialog ()) {if (ofd. ShowDialog () = = DialogResult.OK) {TextBox1.Text = ofd.                FileName; }}} private void Userbutton2_click (object sender, EventArgs e) {if (!string.                IsNullOrEmpty (TextBox1.Text)) {//Click Start Upload, where the actual project requirements are placed in the background threading, in fact, this time-consuming operation should be placed in the background thread System.Threading.Thread Thread = new System.Threading.ThreaD (New System.Threading.ParameterizedThreadStart ((Threaduploadfile))); Thread.                IsBackground = true; Thread.                Start (TextBox1.Text);                userbutton2.enabled = false;            progressBar1.Value = 0;            }} private void Threaduploadfile (object filename) {if (filename is string filename)                {System.IO.FileInfo FileInfo = new System.IO.FileInfo (fileName);                    Start the official upload, about the level three classification, the following is just for example, upload a successful after the server to find files can understand Operateresult result = Integrationfileclient.uploadfile (              FileName,//The full path of the original file that needs to be uploaded, the upload success also needs a condition, the file cannot be occupied Fileinfo.name,                    The file name stored in the server, with the suffix, is generally set to the original file filename "files",//First class classification, indicating the type of file storage, corresponding to the path of the server-side storage inconsistent                    "Personal",//second level classification, indicates the category of file storage, corresponding to the path of the server-side storage Inconsistent "Admin", Class III, indicating the category of file storage, corresponding to the path of the server-side storage inconsistent                    "This file is very important",//The additional description text of this file can be empty ("") "Zhang San",//File uploader, of course you                    You can also do not use the updatereportprogress//File Upload progress report, if you do not need, specify NULL on the line, the general file is larger, the bandwidth is relatively small, need progress tips                );                    Switch to UI foreground display result Invoke (new action<operateresult> (Operateresult = {                    Userbutton2.enabled = true; if (result. issuccess) {MessageBox.Show ("File Upload succeeded!                    ");                        } else {//failure is mostly due to network exception, file does not exist, category name is filled in exception MessageBox.Show ("File upload failed:" + result.)                    Tomessageshowstring ());            }), result); }}///<summary>///For updating upload progress, this method is thread-safe///</summary>//<param NA Me= "sended" > number of bytes uploaded </param>//<param name= "totle" > Total bytes </param> private void updatereportprogress (long sended, long Totle) {if (progressbar1.invoker equired) {Progressbar1.invoke (new Action<long, long> (updatereportprogress), sended, Totle                );            Return            }//Here the code is safe int value = (int) (sended * 100l/totle);        progressBar1.Value = Value; } #endregion

When uploading a file, you can specify additional information, such as the file's descendants and additional descriptive text.

Download file:
        #region File Download Block/******************************************************************************************** * * One instruction to complete the download operation of the file, there are three types of download mode * 1. Specify the file name (with suffix) * 2 that you want to download. Download the data on the server to stream * 3. Download the data from the server to the bitmap picture * **********************************************************************************        ////<summary>///Click on the event that triggered by the file download, if you need to download a file, to pass the full name of the download file///</summary> <param name= "Sender" ></param>//<param name= "E" ></param> private void Userbutt On5_click (object sender, EventArgs e) {//Click to start the download, where the actual project requirements are placed in the background threading, in fact, this time-consuming operation should be placed in the background thread Sys Tem. Threading.thread Thread = new System.Threading.Thread (New System.Threading.ParameterizedThreadStart (            (Threaddownloadfile))); Thread.            IsBackground = true; Thread.            Start (TextBox2.Text);        progressBar1.Value = 0;    }    private void Threaddownloadfile (object filename) {if (filename is string filename) { Operateresult result = Integrationfileclient.downloadfile (fileName,//text                    The name saved on the server, example 123.txt "files",//First class, indicating the category of the file storage, corresponding to the path of the server-side storage inconsistent "Personal",//second level classification, indicating the category of file storage, corresponding to the path of the server-side storage Inconsistent "Admin",//third level classification, indicating File storage category, corresponding to the path inconsistent on server side storage downloadreportprogress,//File download progress report, friendly tips download progress information APPL Ication.                StartupPath + @ "\files\" + filename//download in the text save path, can also be downloaded directly into the MemoryStream data stream, or bitmap);                    Switch to UI foreground display result Invoke (new action<operateresult> (Operateresult = { if (result. issuccess) {MessageBox.Show ("File download succeeded!                    ");                 }   else {//the cause of failure mostly comes from network exceptions, and files do not exist, categorical names are filled with exceptions Messagebox.sho W ("File download failed:" + result.)                    Tomessageshowstring ());            }), result); }}///<summary>///For updating file download progress, this method is thread-safe////</summary>//<param Name= "Receive" > Bytes received </param>//<param name= "totle" > Total bytes </param> private void downl                Oadreportprogress (long receive, long Totle) {if (progressbar2.invokerequired) {                Progressbar2.invoke (New Action<long, long> (downloadreportprogress), receive, totle);            Return            }//Here the code is safe int value = (int) (receive * 100l/totle);        Progressbar2.value = Value; } #endregion

File deletion:
        #regionDelete operations for filesPrivate voidUserbutton1_click (Objectsender, EventArgs e) {            //file deletion does not need to be placed in the background thread, the foreground can be processed, no matter how many large files, are quickly deletedOperateresult result = Integrationfileclient.deletefile ("123.txt","Files","Personal","Admin"); if(result.) issuccess) {MessageBox.Show ("file deletion succeeded! "); }            Else{MessageBox.Show ("file deletion failed due to:"+result.            Tomessageshowstring ()); }        }        #endregion

Get file information for the server:

The above information operation, are specified three folder path, the above example is: "Files", "Personal", "Admin", such as we have uploaded a lot of files in this folder, want to know what files in the folder, and their details, you can call the following methods:

        private void Userbutton4_click (object sender, EventArgs e)        {            //Gets all files for the server-specified directory            operateresult result = Integrationfileclient.downloadpathfilenames (out groupfileitem[] files, "Files", "Personal", "Admin");            if (result. issuccess)            {                treeview1.nodes[0]. Nodes.clear ();                foreach (var file in files)                {                    TreeNode node = new TreeNode (file. FileName);                    Node. Tag = file;                    Treeview1.nodes[0]. Nodes.Add (node);                }                Treeview1.nodes[0]. Expand ();            }            else            {                //Get file name failed                MessageBox.Show (result. Tomessageshowstring ());            }        }

The file information is obtained and stored in the array files, and when we click on the tree node, the details of the file are displayed:

        private void treeView1_AfterSelect (object sender, TreeViewEventArgs e) {TreeNode node = E.node; if (node. Text! = "File list") {TextBox2.Text = node.                Text; if (node.                    Tag is Groupfileitem item) {StringBuilder info = new StringBuilder (); Info.                    Append ("File name:"); Info. Append (item.                    FileName); Info.                    Append (Environment.NewLine); Info.                    Append ("File Size:"); Info. Append (item.                    FileSize); Info.                    Append (Environment.NewLine); Info.                    Append ("File Description:"); Info. Append (item.                    Description); Info.                    Append (Environment.NewLine); Info.                    Append ("Upper-descendant:"); Info. Append (item.                    Owner); Info.                    Append (Environment.NewLine); Info.                    Append ("Upload time:"); Info. Append (item. Uploadtime.tostring()); Info.                    Append (Environment.NewLine); Info.                    Append ("Number of downloads:"); Info. Append (item.                    Downloadtimes); Info.                    Append (Environment.NewLine); TextBox3.Text = info.                ToString (); }            }        }

Get file information for the server:
        private void Userbutton6_click (object sender, EventArgs e)        {            //Gets all files for the server-specified directory            operateresult result = Integrationfileclient.downloadpathfolders (out string[] folders, "Files", "Personal", "");            if (result. issuccess)            {                treeview1.nodes[0]. Nodes.clear ();                foreach (var fold in folders)                {                    TreeNode node = new TreeNode (fold);                    Treeview1.nodes[0]. Nodes.Add (node);                }                Treeview1.nodes[0]. Expand ();            }            else            {                //Get file name failed                MessageBox.Show (result. Tomessageshowstring ());            }        }

This is used to get the name of the sub-file to the server under the files/personal/directory, before the store has an admin

Advanced Apps: Configuring Network Tokens

According to the above server, can be easily accessed by the client, we have not entered the password and so on, as long as the IP and port, other programs can also access your data, in order to be safe, to allow the server-side set of tokens to enhance security, the server-side code is as follows:

        private void Ultimatefileserverinitialization ()        {            ultimatefileserver = new Ultimatefileserver ();                                        Instantiate object            Ultimatefileserver.keytoken = new Guid ("A8826745-84e1-4ed4-ae2e-d3d70a9725b5");            Ultimatefileserver.filesdirectorypath = Application.startuppath + @ "\ultimatefile";   The base path for all file storage            Ultimatefileserver.serverstart (34567);                                                Engine to start a port        }

The client will then need to specify the same token when instantiating, otherwise it will not be able to access the data.

        private void Integrationfileclientinitialization ()        {            //define some properties of the connection server, time-out, IP and port information            Integrationfileclient = new Integrationfileclient ()            {                connecttimeout =,                serveripendpoint = new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("127.0.0.1"), 34567),                keytoken = new Guid (" A8826745-84e1-4ed4-ae2e-d3d70a9725b5 ")                                         //Specify a token            };            Create a path to the local file store            string path = Application.startuppath + @ "\files";            if (! System.IO.Directory.Exists (path))            {                System.IO.Directory.CreateDirectory (path);            }        }
To configure logging:

Primarily for server-side logging:

        private void Ultimatefileserverinitialization ()        {            ultimatefileserver = new Ultimatefileserver ();                                        Instantiate object            Ultimatefileserver.keytoken = new Guid ("A8826745-84e1-4ed4-ae2e-d3d70a9725b5");       Specifies a token            ultimatefileserver.lognet = new HslCommunication.LogNet.LogNetSingle (Application.startuppath + @ "\logs \123.txt ");            Ultimatefileserver.filesdirectorypath = Application.startuppath + @ "\ultimatefile";   The base path for all file storage            Ultimatefileserver.serverstart (34567);                                                Engine to start a port        }
The number of files under the specified directory is monitored:

For example, we need to implement the function of this directory ("Files", "Personal", "Admin") the number of files to monitor, when there is file upload, delete, to trigger the message, such as the following example shows, the server-side interface to add a new data to display the total number of files in this directory information.

        private void Ultimatefileserverinitialization () {ultimatefileserver = new ultimatefileserver (); Instantiate object Ultimatefileserver.keytoken = new Guid ("A8826745-84e1-4ed4-ae2       E-d3d70a9725b5 "); Specifies a token ultimatefileserver.lognet = new HslCommunication.LogNet.LogNetSingle (Application.startuppath + @ "\log            S\123.txt ");   Ultimatefileserver.filesdirectorypath = Application.startuppath + @ "\ultimatefile";                                                Base path for all file storage Ultimatefileserver.serverstart (34567); Start a port engine//subscribe to a directory of information, using the file Set container implementation Groupfilecontainer container = Ultimatefileserver.getgroupfromfi            Lepath (Application.startuppath + @ "\ultimatefile\files\personal\admin"); Container.                         Filecountchanged + = container_filecountchanged;           triggered when the number of files has changed} private void container_filecountchanged (int obj) { if (invokerequired) {Invoke (new action<int> (container_filecountchanged), obj);            Return } Label1. Text = "Number of files:" + obj.        ToString (); }

Sample interface:

The source code of the project is disclosed, please follow the MIT agreement, address: Https://github.com/dathlin/FileManagment

C # File upload download function for file Management engine development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.