Analysis on how ASP. NET + XML creates a network Hard Disk

Source: Internet
Author: User

Common transmission modes and difficulties in specific environments

We often have the following application requirements: resources are shared by exchanging public data files over the network, protecting private data from unauthorized access, and using simple and intuitive operations. Our common file transmission methods include FTP, Email, and network neighbors. Among them, "Ftp" is the most powerful, but it is a little complex to use, a lot of settings are enough to let many people stop, especially when the number of users is unpredictable, user settings for special needs will be more complicated; "Email" is familiar to everyone, but its transmission requires you not only to connect to the Internet, but also its security is also a problem, within an enterprise, it is not a good way to exchange documents such as finance and labor resources. "Network neighbors" are another method for transferring documents, by specifying shared Web folders on the local machine and placing resource files, users within a certain range can access these files. However, this method is widely used, generally, users in the same DNS segment can access the domain name smoothly. Other users, especially those on the Internet, are difficult to use. In addition, similar to Email, the domain name is not intuitive, most of the time, you have to expand the search layer by layer on many list computers to obtain the resources you want!

From this point of view, although the above three methods have achieved the communication of file data to a certain extent, however, they are mainly oriented to "point-to-point" transmission (you can only passively wait for the other party to place data, rather than actively "Visually" requests), and cannot implement "one space, resource Exchange "application requirements, this" Point-to-multiple "based sharing method needs to seek another transmission channel, network hard disk is a good solution.

  Advantages of network Hard Disks

A network hard disk (also called a shared space) is a hard disk space on the server. If you have sufficient permissions, you can operate it at will, just like using your local computer. You must know that all of this is transmitted over Http and displayed in front of all users in the form of Web. You can use a browser to access it. In this way, "a space, the sharing mode of resource mutual view is realized!

In addition, the network hard disk interface runs on the client. It allows users to submit data to the server and manage the information within the specified range. This processing mode is widely used in actual development, especially in the construction of an interactive network document management system: Online examination system, file transmission system, news and publishing system, and the company bidding system have a large number of applications!

The following uses Asp.net (implemented in Visual C #) and Xml (Extensible Markup Language) to develop such a network hard drive system. Detailed descriptions of program development details and Key Technologies and difficulties used in code are provided. You can develop your own network hard drive by referring to these instructions.

Functions of network Hard Disks

Our network hard drive provides the following features:

1. View folder content

2. You can set access permissions when creating a new folder.

3. jump between folders: Go to the next level and return to the previous level

4. upload a file to a specified folder

5. download the file to your local computer or view the file content online.

6. delete files or folders

 Development details and key technical points

  1. view the folder content:

At the beginning, the program will enter the specified root folder (such as \ NetHard). The content in this folder will be displayed in the list through the data binding control (DataGrid), including the following: category (difference folder or file), name, permission (whether to allow access to the folder? Can an object be downloaded ?) , Delete (Are you allowed to delete files or folders ?) And the creator of the folder. Here, because the content in the folder changes dynamically (you Don't know when a user transfers files, creates folders, or deletes them ), we dynamically create a data table able to read the content in the specified folder and bind it to the display control DataGrid as a data source. In this way, data display is always timely. The function for creating a dynamic table is as follows:
Copy codeThe Code is as follows:
Public DataTable Bind (string fullFolderPath) // create a data table to read the folder content
{
// The following describes how to dynamically create a data table:
DataTable dt = new DataTable ();
DataRow dr;
// Create a data table structure
Dt. Columns. Add (new DataColumn ("type", System. Type. GetType ("System. String"); // type
Dt. Columns. Add (new DataColumn ("name", System. Type. GetType ("System. String"); // name
Dt. Columns. Add (new DataColumn ("action", System. Type. GetType ("System. String"); // operation
Dt. Columns. Add (new DataColumn ("owner", System. Type. GetType ("System. String"); // creator
// Fill in data for each row
Foreach (string d in Directory. GetFileSystemEntries (fullFolderPath )){
Dr = dt. NewRow (); // create a new row
String [] parts = d. Split (new char [] {'\'});
String txt = parts [parts. Length-1]; // obtain the last part of the string, which may be a file name or folder
Dr [1] = txt; // name
If (File. Exists (d) // if it is a File
{
Dr [0] = "file"; // type
Int pos = currFullPath. IndexOf ("NetHard ");
String relaUrl = currFullPath. Substring (pos );
String
Url = "http: // 10.80.50.1/SharedSpace/" + relaUrl + "/" + txt ;//
10.80.50.1 is the author's server address. You should modify it to your server address.
Dr [2] = "<a href =" + url + "target = _ blank" + "> download </a> ";
}
Else if (Directory. Exists (d) {// if it is a folder
Dr [0] = "folder"; // type
String password = GetFolderPassword (d); // get the folder password information
Int type = GetFolderLimitType (d );
If (password! = "No") & (type! = 1 ))
Dr [2] = "<
Href = PasswordValidate. aspx? Path = "+ d +"> seal </a> "; // action
Else
Dr [2] = "<a href = Default. aspx? Path = "+ d +"> enter </a> "; // action
Dr [3] = GetFolderOwner (d); // get the name of the folder creator
}
Else
Response. Write ("<script> alert ('no object can be bound! ') </Script> ");
Dt. Rows. Add (dr); // Add a row
Return dt; // return data table
}
}

This method extracts the content in the specified folder for processing separately: if it is a file, the "Download" link is displayed pointing to the Url of the file on the server; the folder needs to be further differentiated depending on whether the folder is protected or not and the Protection Type: If "restricted access" is displayed, "sealed" is imported to the password verification page. When "not restricted access" is entered, the query string is modified, the show "go" link points to the initial display page.

  2. Create a new folder and set access permissions:

After entering the new folder name, you can create a new folder in the current path. The remote creation of a new folder in Asp.net is exactly the same as the local machine operation, which is very simple ,. net IO namespace provides a dedicated class library Directory, which can be implemented by calling its method. The statement is as follows:

Directory. CreateDirectory (string directory)

Specifically, the string directory indicates the complete path of the new folder. By default, this method opens full read/write permissions for the new folder to all users. In special cases, you can also manually create the root folder shared by the Network hard disk (the "NetHard" folder in the program, you can change it, you need to manually set the write permission for this folder. Under IIS, you can run the "permission wizard" on this folder under "internet Information Service" to set the access permission.

Security should be considered during resource sharing. Here, you can set the user's access permission to the folder. By setting the password, you can specify whether to allow the user to enter the folder, whether to allow the user to delete the folder, or both. In this way, you can protect your files, exclusively access them, or restrict them to a specific range (members in this range should know your password). In this way, the product R & D department can share one folder, and the finance department can share another folder in the same way. People who do not belong to this department will be restricted. Of course, you can also apply this restriction to a single file (there seems to be not many such applications, and the program is not implemented ).

In addition, to manage these folders, you need to keep their settings: folder name, location, restricted operation type, password, and creator. The program writes the information into an Xml file (this is folder. and then perform various management operations on the folder by reading and writing the xml file. The following method implements the storage of information set when creating a folder:
Copy codeThe Code is as follows:
Public void CreateXmlOrAddFrag (string xmlFullPath, string
FolderFullPath, string owner, string password, int type ){
XmlDocument xmlDoc = new XmlDocument ();
String xml = "";
String xmlNode = "<character> ";
XmlNode + = "<fullPath> ";
XmlNode + = folderFullPath;
XmlNode + = "</fullPath> ";
XmlNode + = "<owner> ";
XmlNode + = owner;
XmlNode + = "</owner> ";
XmlNode + = "<password> ";
XmlNode + = password;
XmlNode + = "</password> ";
XmlNode + = "<type> ";
XmlNode + = type;
XmlNode + = "</type> ";
XmlNode + = "</character> ";
If (! File. Exists (xmlFullPath) {// create an xml storage File if the File does not exist
Xml = "<? Xml version = '1. 0' encoding = 'gb2312 '?> ";
Xml + = "<folder> ";
Xml + = xmlNode;
Xml + = "</folder> ";
XmlDoc. LoadXml (xml );
XmlDoc. Save (xmlFullPath); // stores files
}
Else {// If an xml storage file exists, add a new file segment.
XmlDoc. Load (xmlFullPath );
XmlDocumentFragment
DocFrag = xmlDoc. CreateDocumentFragment (); // File Fragment Element Node
DocFrag. InnerXml = xmlNode;
XmlNode currNode = xmlDoc. DocumentElement; // obtain the root node of the document.
CurrNode. InsertBefore (docFrag, currNode. FirstChild); // insert a document segment
XmlDoc. Save (xmlFullPath); // Storage Change
}
}

The fileFullPath parameter is the xml file path for storing Folder Information, folderFullPath is the path of the new folder, owner is the creator name, and password is the password, type indicates the type of the operation to be restricted ("0" indicates restricted access, "1" indicates restricted deletion ). The folder that stores folder Information at the beginning of the program running. the xml file may not exist. Therefore, the program first checks whether the file exists. If the file does not exist, it dynamically creates the file. When creating a folder, you only need to add a file segment. Here, the reading and writing of Xml files is implemented through the DOM (Document Object Model). Because the Xml file is not too large here, this method does not require too high memory resources and the speed will be very fast!

  3. Operations on files and folders:

Operations on files include "Download" and "delete". When the content in the specified folder is displayed in the list above, the statement is as follows:

Dr [2] = "<a href =" + url + "target = _ blank" + "> download </a>"; // create a connection address

The url is the server path corresponding to the specified file. Use this link to locate the file to the corresponding location on the server. Depending on the file format, the client can download the file to the local machine or open it on the server.

Deleting a File is simple. The File class library in the. Net I/O namespace has the following method:

File. Delete (string filename); where, filename is the complete path of the File

You need to note that the deletion of a file does not require verification. To prevent the file from being deleted, you need to follow the methods below. (Of course, the program provides confirmation and verification to prevent accidental deletion of files, and the same is true for Folder deletion !)

Operations on folders are divided into: enter or delete. If a folder is set to "restricted access" or "restricted deletion" during creation, the user will be required to verify the password when performing such an operation. The corresponding operations can only be completed after the operation is verified, this method protects your files from unauthorized access or deletion.

Folder deletion programs are more complex than file deletion ,. the Delete () method provided by the Directory class library of. Net can only Delete empty folders. Therefore, you need to clear the contents of the folder before you can complete this operation, because the folder may contain folders again, we can call this operation recursively:
Copy codeThe Code is as follows:
// Delete a folder
Public void DeleteFolder (string dir)
{
Foreach (string d in Directory. GetFileSystemEntries (dir ))
{
If (File. Exists (d ))
File. Delete (d); // Delete the File directly.
Else
DeleteFolder (d); // recursively Delete subfolders
}
Directory. Delete (dir); // Delete an empty folder
}

The dir parameter is the complete path of the folder to be deleted. The program uses a loop statement to find the content in the folder. if the content is a file, it is directly deleted. if the content is a folder, it recursively calls the method itself to delete the subfolders. After the folder is cleared, the deletion operation is completed.

 4. File Upload:

To implement the functions of the network hard disk, you must have files available for operation. These files are uploaded from the client (of course, the server can also provide these files, but this is not the focus of the network hard disk). In the past, we used to upload files. In Asp, we usually used the first File Upload Component, such as Microsoft's PostingAcceptor component, in addition, there are some paid components provided by third parties (but to be honest, these components are not easy to use ). At that time, it was quite tedious to develop such a File Upload Component ,. the class libraries HttpPostedFile and HttpFilesCollection provided by Net can easily access the files uploaded to the server and allow developers to control the File Upload process. The HttpPostedFile class encapsulates the file objects that have been uploaded to the server. Its method and attributes provide access to the content and attributes of each file. The HttpFileCollection class provides a container for multiple HttpPostedFile objects, this class is used to save the data structure uploaded to the server, so that you can use the transferred file set, which can be accessed from the HttpRequest object through its Files attribute, once the server receives the entire request content, this set can be accessed. These built-in components make it quite easy to upload files in Asp.net, and you only need a few lines of code! There are many articles about how to upload files in Asp.net. I will not elaborate them here. If you need them, you can refer to those articles. Here, I will only remind you to pay attention to the following points:

1) set the encoding type Enctype of the client form to the MIME format of multipart/form-data. submit the form using the Http post method, as shown below:

<Form id = "form1" method = "post" enctype = "multipart/form-data" runat = "server">

2) The HttpInputFile control runs on the server and sets runat = server and type = file, as shown below:

<INPUT id = "fileUp" type = "file" size = "6" runat = "server">

3) to upload multiple Files, you can configure multiple HttpInputFile controls and use HttpRequest. Files to obtain these Files.

  5. Environment configuration file Web. config processing:

In the Chinese state, you may need to encode the globalization settings from the default "Utf-8" to "gb2312", the statement is as follows:

Copy codeThe Code is as follows:
<Globalization
RequestEncoding = "gb2312"
ResponseEncoding = "gb2312"
/>


At the same time, the default file size limit set by Web. config may not meet your needs. You may need to enlarge the limit. This is achieved by modifying the value of the maxRequestLength parameter, as shown below:
Copy codeThe Code is as follows:
<! -- Set the maximum number of acceptable bytes -->
<HttpRuntime maxRequestLength = "500000">
</HttpRuntime>


  6. Keep track of the "current path" value at any time:

Another key point in the program is about "current path", because you always need to jump between different folders: click "enter" to reach the next level folder, click "top-level folder" to return to the top-level folder. The contents of all these folders are displayed on the same page (Default. aspx) to display, this display page is set to always display the content of the current folder. When you send a query string to call it, you need to include the complete expression of the current path in the query string, which is achieved by setting a static variable in the program: public static string currFullPath = ""; when the current path changes, this path value is always transmitted to this static scalar:

CurrFullPath = Request ["path"]; this makes the static variable always store the current path value. The query string call page is Response. redirect ("Default. aspx? Path = "+ currFullPath) is always displayed in the current folder!

  References:

Asp.net programmer reference manual, XML advanced programming, C # advanced programming, Microsoft MSDN

  Running environment:

The program is successfully debugged under Windows XP Chinese official version,. Net Frameworks official version, and Visual Studio. Net Chinese official version, and runs stably on the LAN (Headquarters + Multiple Remote subsidiaries ).

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.