IIS-built HTTP file server

Source: Internet
Author: User
Tags windows 10 enterprise

HTTP file server built by IIS using the C#webclient class to access (upload/download/delete/list file directories)

Objective

Why do you write this blog? In fact, is the use of the C#webclient class to access the HTTP file server built by IIS The problem took me a full two days, therefore, it is necessary to write down what you have learned, at the same time, you can let the vast number of Bo friends learn a bit.

If there are deficiencies in this article, please leave a message below, I will make corrections, thank you!

Building an IIS file server

This blog post uses the operating system for Windows 10 enterprise, similar to other Windows systems, please learn from:

First, of course, there must be no IIS at the beginning, so what should I do? Need a software environment to build, the specific method is as follows:

1) Open "Control Panel" and locate "programs and features" as shown in:

2) Click to go to "Enable or disable Windows features" as shown in:

3) After entering, tick all the nodes under "Internet Information Services" (so that a fully functional HTTP/FTP server is built), and note that the "WebDAV release" must be installed, This is very much related to file access permissions in the file server, and if you want to read and write to a folder in the server that has read and write permissions, you must turn on this option, as shown in:

4) Wait for the installation to complete, please be patient, as shown in:

5) When finished, click the "Close" button, then, open "Control Panel" and find "Administrative Tools" as shown in:

6) After tapping "Administrative Tools", locate "Internet information Services (IIS) Manager" and open it as shown in:

7) After entering, it has entered the IIS management interface, we only use the function as red box in the IIS function, as shown in:

8) First build IIS, a default Web site will appear, we will move the mouse over the "Default Web Sites" above, right-click the popup menu, in the menu, tap "Delete" to delete the site, as shown in:

9) Add your own website, mouse over the "website", right click on the mouse, pop-up menu, click "Add Site" in the menu, as shown in:

10) According to the steps described, fill in the Site name and select the physical path, the other default can be, and then click the "OK" button:

11) This website is only as a file server, therefore, the server's file browsing function opens, in order to browse, the specific action for the mouse double-click "Directory Browsing", the "action" in the column "Enable" opens, as shown in:

12) Mouse Double-click on "WebDAV authoring rules" as shown in:

13) Click "WebDAV Settings" as shown in:

14) Set the property in the red box shown in ①② to the attribute shown in the figure, and click "Apply" as shown in:

15) go back to "WebDAV authoring rules" and click "Add Authoring Rule" as shown in:

16) in the popup "Add Authoring Rule", "Allow access to this content" check, the permission "read, source, write" Tick, click the "OK" button to close, as shown in:

17) Return to "WebDAV authoring rules" and click "Enable WebDAV" as shown in:

18) Double-click Authentication to enable anonymous authentication (client read file) and Windows authentication (client write, delete) as follows:

19) in order to allow the file server to have write, delete function, you can create a new account on the existing Windows System account "test" (Password: 123), as shown in:

The above about how to create account content, please Baidu

20) in order for the test account to have a smooth access to the "testwebsite" folder stored under E, you need to set the access rights for the Power Users group to that folder, as shown in:

For questions about how to set permissions for a specific group or user, please Baidu

21) To view the IP address of the native IIS and enter the IP in the browser, the following will be displayed, as shown in:

22) Since then, the construction of the IIS file server has been completed.

Accessing the IIS file server using C#webclient

This blog is used by the IDE as VS2015, before using the WebClient class, you must refer to the System.Net namespace, file download, upload and delete using asynchronous programming, you can also use synchronous programming,

Here is an example of asynchronous programming:

1) file Download:

 1 static void Main (string[] args) 2 {3//Definition _webclient Object 4 WebClient _webclient = New WebClient (); 5//Use default credentials-when reading, only the default credentials can be 6 _webclient.credentials = CredentialCache.DefaultCredentials; 7//Download the link address (file server) 8 uri _uri = new Uri (@ "Http://192.168.1.103/test.doc");             9//Registration Download Progress Event notification _webclient.downloadprogresschanged + = _webclient_downloadprogresschanged;11 Register download Complete Event notification _webclient.downloadfilecompleted + = _webclient_downloadfilecompleted;13//Async         Download to D-disk _webclient.downloadfileasync (_uri, @ "D:\test.doc"); 16}17 18 Download completion event handler for private static void _webclient_downloadfilecompleted (object sender, SYSTEM.COMPONENTMODEL.A Synccompletedeventargs e) {Console.WriteLine ("Download completed ..."); 22}23 24/ /Download Progress event handlers for private Static void _webclient_downloadprogresschanged (object sender, DownloadProgressChangedEventArgs e) Sole.   WriteLine ($ "{e.progresspercentage}:{e.bytesreceived}/{e.totalbytestoreceive}"); 28}

The results of the operation are as follows:

2) File Upload:

        static void Main (string[] args) {//define _webclient object WebClient _webclient = new Webclie            NT ();            Use Windows logon mode _webclient.credentials = new NetworkCredential ("Test", "123");            Uploaded link address (file server) Uri _uri = new Uri (@ "Http://192.168.1.103/test.doc");            Registration upload Progress Event notification _webclient.uploadprogresschanged + = _webclient_uploadprogresschanged;            Register upload Complete Event notification _webclient.uploadfilecompleted + = _webclient_uploadfilecompleted;            Asynchronously uploads files from the D disk to the server _webclient.uploadfileasync (_uri, "PUT", @ "D:\test.doc");        Console.readkey (); }//Download completion event handler private static void _webclient_uploadfilecompleted (object sender, Uploadfilecompletedeventarg        S e) {Console.WriteLine ("Upload completed ..."); }//Download progress event handler private static void _webclient_uploadprogresschanged (object sender, Uploadprogresschangedeven      Targs e) {      Console.WriteLine ($ "{e.progresspercentage}:{e.bytessent}/{e.totalbytestosend}"); }

The results of the operation are as follows:

3) file deletion:

        static void Main (string[] args)        {            //define _webclient object            WebClient _webclient = new WebClient ();            Use Windows logon mode            _webclient.credentials = new NetworkCredential ("Test", "123");            File link Address to delete (file server)            uri _uri = new Uri (@ "Http://192.168.1.103/test.doc");            Register Delete event (simulated delete)            _webclient.uploaddatacompleted + = _webclient_uploaddatacompleted;            Asynchronously deletes files from a file (impersonation)            _webclient.uploaddataasync (_uri, "delete", new byte[0]);            Console.readkey ();        }        Delete Completion event handler        private static void _webclient_uploaddatacompleted (object sender, UploadDataCompletedEventArgs e)        {            Console.WriteLine ("Deleted ...");        }

The results of the operation are as follows:

4) List files (or directories):

Namespaces to be introduced: System.IO, System.Xml, and system.globalization

        static void Main (string[] args) {sortedlist<string, serverfileattributes> _results =getco            Ntents (@ "http://192.168.1.103", true); Output file (or directory) information in console: foreach (var _r in _results) {Console.WriteLine ($ "{_r.key}:\r\nnam                E:{_r.value.name}\r\nisfolder:{_r.value.isfolder} ");                Console.WriteLine ($ "value:{_r.value.url}\r\nlastmodified:{_r.value.lastmodified}");            Console.WriteLine ();        } console.readkey ();            }//define properties for each file or directory struct Serverfileattributes {public string Name;            public bool Isfolder;            public string Url;        Public DateTime lastmodified;         }//List files or directories static sortedlist<string, serverfileattributes> getcontents (string serverurl, bool deep)            {HttpWebRequest _httpwebrequest = (HttpWebRequest) httpwebrequest.create (ServerURL); _httpwebrequest.headeRs.            ADD ("Translate:f");            _httpwebrequest.credentials = CredentialCache.DefaultCredentials; String _requeststring = @ "<?xml version=" "1.0" "encoding=" "Utf-8" "?>" + @ "<a:propfind xmlns:a=" DAV: "" > "+" <a:prop> "+" <a:displayname/> "+" <a:isco Llection/> "+" <a:getlastmodified/> "+" </a:prop> "+" &L            T;/a:propfind> ";            _httpwebrequest.method = "PROPFIND";            if (deep = = True) _httpwebrequest.headers.add ("depth:infinity");            else _httpwebrequest.headers.add ("depth:1");            _httpwebrequest.contentlength = _requeststring.length;            _httpwebrequest.contenttype = "Text/xml";            Stream _requeststream = _httpwebrequest.getrequeststream (); _requeststream.write (Encoding.ASCII.GetBytes (_requeststring), 0, Encoding.ASCII.GetBytes (_requeststring).            Length);            _requeststream.close ();            HttpWebResponse _httpwebresponse;            StreamReader _streamreader;                try {_httpwebresponse = (HttpWebResponse) _httpwebrequest.getresponse ();            _streamreader = new StreamReader (_httpwebresponse.getresponsestream ());            } catch (WebException ex) {throw ex;            } StringBuilder _stringbuilder = new StringBuilder ();            char[] _chars = new char[1024];            int _bytesread = 0;            _bytesread = _streamreader.read (_chars, 0, 1024);                while (_bytesread > 0) {_stringbuilder.append (_chars, 0, _bytesread);            _bytesread = _streamreader.read (_chars, 0, 1024);            } _streamreader.close ();            XmlDocument _xmldocument = new XmlDocument ();            _xmldocument.loadxml (_stringbuilder.tostring ()); XmlnamespacEmanager _xmlnamespacemanager = new XmlNamespaceManager (_xmldocument.nametable);            _xmlnamespacemanager.addnamespace ("A", "DAV:");            XmlNodeList _namelist = _xmldocument.selectnodes ("//a:prop/a:displayname", _xmlnamespacemanager);            XmlNodeList _isfolderlist = _xmldocument.selectnodes ("//a:prop/a:iscollection", _xmlnamespacemanager);            XmlNodeList _lastmodifylist = _xmldocument.selectnodes ("//a:prop/a:getlastmodified", _xmlNamespaceManager);            XmlNodeList _hreflist = _xmldocument.selectnodes ("//a:href", _xmlnamespacemanager); sortedlist<string, serverfileattributes> _sortedlistresult = new sortedlist<string, ServerFileAttributes            > ();            Serverfileattributes _serverfileattributes; for (int i = 0; i < _namelist.count; i++) {if (_hreflist[i]. Innertext.tolower (New CultureInfo ("en-us")). TrimEnd (new char[] {'/'})! = Serverurl.tolower (New CultureInfo ("en-us")). TrimEnd (New Char[] {'/'}) {_serverfileattributes = new serverfileattributes (); _serverfileattributes.name = _namelist[i].                    InnerText; _serverfileattributes.isfolder = Convert.toboolean (Convert.ToInt32 (_isfolderlist[i).                    InnerText)); _serverfileattributes.url = _hreflist[i].                    InnerText; _serverfileattributes.lastmodified = Convert.todatetime (_lastmodifylist[i].                    InnerText);                _sortedlistresult.add (_serverfileattributes.url, _serverfileattributes);        }} return _sortedlistresult; }

The results of the operation are as follows:

IIS-built HTTP file server

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.