Add a GetInputStream Extension Method to string.

Source: Internet
Author: User
Tags ftp protocol

Add a GetInputStream Extension Method to string.

Sometimes, we need to read some data, regardless of whether the data is from the data file on the disk or from the network. Therefore, the following StringExtensions. cs is available:

 
 1 using System; 2 using System.IO; 3 using System.Net; 4  5 namespace Skyiv 6 { 7   public static class StringExtensions 8   { 9     public static Stream GetInputStream(this string fileNameOrUri, string user = null, string password = null)10     {11       if (!Uri.IsWellFormedUriString(fileNameOrUri, UriKind.Absolute)) return File.OpenRead(fileNameOrUri);12       var uri = new Uri(fileNameOrUri);13       if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) return uri.GetHttpStream();14       if (uri.Scheme == Uri.UriSchemeFtp) return uri.GetFtpStream(user, password);15       if (uri.Scheme == Uri.UriSchemeFile) return uri.GetFileStream();16       throw new NotSupportedException(Notsupported uri scheme:  + uri.Scheme);17     }18 19     static Stream GetFtpStream(this Uri uri, string user = null, string password = null)20     {21       var ftp = (FtpWebRequest)WebRequest.Create(uri);22       if (user != null && user != anonymous && user != ftp)23         ftp.Credentials = new NetworkCredential(user, password);24       ftp.Method = WebRequestMethods.Ftp.DownloadFile;25       return ((FtpWebResponse)ftp.GetResponse()).GetResponseStream();26     }27 28     static Stream GetHttpStream(this Uri uri)29     {30       return ((HttpWebResponse)((HttpWebRequest)WebRequest.Create(uri)).GetResponse()).GetResponseStream();31     }32 33     static Stream GetFileStream(this Uri uri)34     {35       return ((FileWebResponse)((FileWebRequest)WebRequest.Create(uri)).GetResponse()).GetResponseStream();36     }37   }38 }

In the above program:

  1. The GetInputStream Extension Method of rows 9th to 17 returns the input stream of the data to be read.
  2. Line 3 calls the static method IsWellFormedUriString Of The Uri class to determine whether to read data from the network. If not, call the static method OpenRead of the File class to obtain the input stream.
  3. Line 3 constructs an instance of the Uri class.
  4. Line 3 processes the input using http or https.
  5. Row 3 processes the input using the ftp protocol.
  6. Row 3 processes the input using the file protocol.
  7. To handle other protocols in line 16th, A NotSupportedException exception is thrown directly, indicating that only the above four protocols are supported.
  8. The GetFtpStream Extension Method of rows 19th to 26 is used to obtain the input stream of the response data sent on the FTP server. It can be anonymous or non-Anonymous.
  9. The GetHttpStream Extension Method of lines 28th to 31 is used to obtain network streams using http or https.
  10. The GetFileStream Extension Method of lines 33rd to 36 is used to obtain the data stream of the local disk file system using the file protocol.

    The CopyTester. cs for testing is as follows:

     1 using System.IO; 2  3 namespace Skyiv.Test 4 { 5   static class CopyTester 6   { 7     static void Main(string[] args) 8     { 9       args[0].GetInputStream().CopyTo(File.Create(args[1]));10     }11   }12 }

    The function of this test program is to copy data. Two command line parameters are required:

    1. The first command line parameter specifies the data source, which can be a local disk file or network data. It supports https, http, ftp, and file protocols. Of course, the file protocol actually reads local disk files.
    2. The second command line parameter specifies the name of the local disk file to be copied.

      The content of the above test procedure is the statement of Line 1:

      1. Use the first command line parameter args [0] To Call The GetInputStream Extension Method of the String class to obtain the input stream.
      2. Call the CopyTo method of the Stream class to copy the input Stream to the output Stream.
      3. The output stream is obtained by using the static File method Create.

        Compile and run in Windows:

        E: work>Csc CopyTester. cs StringExtensions. csMicrosoft (R) Visual C #2010 compiler 4.0.30319.1 copyright (C) Microsoft Corporation. All rights reserved. E: work>CopyTester https://github.com/mono/xsp/zipball/master mono-xsp.zipE: work>CopyTester http://mysql.ntu.edu.tw/Downloads/Connector-Net/mysql-connector-net-6.5.4-noinstall.zip mysql-connector.zipE: work>CopyTester ftp://ftp.ntu.edu.tw/pub/MySQL/Downloads/Connector-Net/mysql-connector-net-6.5.4-noinstall.zip mysql-connector.2.zipE: work>CopyTester file: /// E:/work/mysql-connector.zip mysql-connector.3.zipE: work>CopyTester mysql-connector.zip mysql-connector.4.zipE: work>Dir *. zipMono-xsp.zip2012/468,024 mysql-connector.2.zip2012/03/11 mysql-connector.3.zip2012/4,176,361 mysql-connector.4.zip2012/03/11 4,176,361 mysql-connector.zip/03/11 4,176,361

        The above tests respectively read network data using https, http, ftp, and file protocols, and read data from local disks. Note that the file protocol actually reads data from the local disk.

        Compile and run in Linux:

        ben@vbox:~/work> dmcs CopyTester.cs StringExtensions.csben@vbox:~/work> mono CopyTester.exe http://mysql.ntu.edu.tw/Downloads/Connector-Net/mysql-connector-net-6.5.4-noinstall.zip mysql-connector.zipben@vbox:~/work> mono CopyTester.exe ftp://ftp.ntu.edu.tw/pub/MySQL/Downloads/Connector-Net/mysql-connector-net-6.5.4-noinstall.zip mysql-connector.2.zipben@vbox:~/work> mono CopyTester.exe file:///home/ben/work/mysql-connector.zip mysql-connector.3.zipben@vbox:~/work> mono CopyTester.exe mysql-connector.zip mysql-connector.4.zipben@vbox:~/work> ls -l *.zip-rw-r--r-- 1 ben users 4176361 Mar 11 09:54 mysql-connector.2.zip-rw-r--r-- 1 ben users 4176361 Mar 11 10:01 mysql-connector.3.zip-rw-r--r-- 1 ben users 4176361 Mar 11 10:01 mysql-connector.4.zip-rw-r--r-- 1 ben users 4176361 Mar 11 09:53 mysql-connector.zip

        In Windows, the https data stream on the network can be normally read, but fails in Linux:

        ben@vbox:~/work> mono CopyTester.exe https://github.com/mono/xsp/zipball/master mono-xsp.zipUnhandled Exception: System.Net.WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010a  at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates) [0x00000] in :0  at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 () [0x00000] in :0  at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00000] in :0  at (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process ()  at Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg) [0x00000] in :0  at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] in :0  --- End of inner exception stack trace ---  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in :0  --- End of inner exception stack trace ---  at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in :0  at System.Net.HttpWebRequest.GetResponse () [0x00000] in :0  at Skyiv.StringExtensions.GetHttpStream (System.Uri uri) [0x00000] in :0  at Skyiv.StringExtensions.GetInputStream (System.String fileNameOrUri, System.String user, System.String password) [0x00000] in :0  at Skyiv.Test.CopyTester.Main (System.String[] args) [0x00000] in :0[ERROR] FATAL UNHANDLED EXCEPTION: System.Net.WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010a  at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates) [0x00000] in :0  at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 () [0x00000] in :0  at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00000] in :0  at (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process ()  at Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg) [0x00000] in :0  at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] in :0  --- End of inner exception stack trace ---  at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in :0  --- End of inner exception stack trace ---  at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in :0  at System.Net.HttpWebRequest.GetResponse () [0x00000] in :0  at Skyiv.StringExtensions.GetHttpStream (System.Uri uri) [0x00000] in :0  at Skyiv.StringExtensions.GetInputStream (System.String fileNameOrUri, System.String user, System.String password) [0x00000] in :0  at Skyiv.Test.CopyTester.Main (System.String[] args) [0x00000] in :0

        I don't know if it is my openSUSE 12.1 operating system or the Mono 2.10.6 runtime environment. Some configuration is required to meet the https security verification requirements. However, I have not made any special configuration in Windows. In addition, you can use the wget command in Linux to download https data:

        ben@vbox:~/work> wget https://github.com/mono/xsp/zipball/masterasking libproxy about url 'https://github.com/mono/xsp/zipball/master'libproxy suggest to use 'direct://'--2012-03-11 13:48:32--  https://github.com/mono/xsp/zipball/masterResolving github.com (github.com)... 207.97.227.239Connecting to github.com (github.com)|207.97.227.239|:443... connected.HTTP request sent, awaiting response... 302 FoundLocation: https://nodeload.github.com/mono/xsp/zipball/master [following]asking libproxy about url 'https://nodeload.github.com/mono/xsp/zipball/master'libproxy suggest to use 'direct://'--2012-03-11 13:48:34--  https://nodeload.github.com/mono/xsp/zipball/masterResolving nodeload.github.com (nodeload.github.com)... 207.97.227.252Connecting to nodeload.github.com (nodeload.github.com)|207.97.227.252|:443... connected.HTTP request sent, awaiting response... 200 OKLength: 468024 (457K) [application/octet-stream]Saving to: `master'100%[======================================>] 468,024  46.5K/s in 17s2012-03-11 13:48:54 (27.0 KB/s) - `master' saved [468024/468024]ben@vbox:~/work> mv master mono-xsp.zip

        In this case, the HttpWebRequest class in the Mono environment may need some settings to read https data. If any of you know, please let me know in the comments in this article. Thank you.

         

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.