C # implements file download and supports resumable upload

Source: Internet
Author: User

Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. IO;
Using system. text;
Using system. net;
Namespace simpledemo
{

Class Program
{
/// <Summary>
/// Download Reserved Words
/// </Summary>
Public static string persist_exp = ". cdel ";
/// <Summary>
Public static void main (string [] ARGs)
{

String Path = "d :\\ aa.txt ";

String EC = getfileencoding (path, "gb2312 ");
Print ("coding:" + EC );

// String content = filereader (path, encoding. getencoding (EC ));
// Print (content );

// Filewriter (path, "Test content 11", encoding. getencoding (EC ));

String url = "http://www.XXX.com/20120920172200024.flv ";
String path1 = "d :\\ aa1.flv ";

Download (URL, path1 );
// Gapdownload (URL, path1 );
// T (URL );

}
Public static void T (string URL ){

Httpwebrequest request = (system. net. httpwebrequest) httpwebrequest. Create (URL );

// Webresponse response = httpclient. creategethttpresponse (URL, 3000, null, null );

Try {

Webresponse response = request. getresponse ();

Webheadercollection headers = response. headers;

Print (response. contentlength );

Request = (system. net. httpwebrequest) httpwebrequest. Create (URL );
Request. addrange (11); // sets the range value.
Webresponse response1 = request. getresponse ();
Print (response1.contentlength );

Foreach (string key in headers)
{
Print (Key + "-----" + headers. Get (key ));
}

String disposition = headers. Get ("content-disposition ");

Print (Disposition );
} Catch (exception e ){
Print (E. Message );
}

// String filename = disposition. substring (Disposition. indexof ("\""));

// Print (filename );

}
Public static void download (string URL, string path ){
If (file. exists (PATH ))
{
Print ("the file already exists! Download again? ");
Return;
}
Else {
Path = path + persist_exp;

Simpledownload (URL, PATH); // start download
}
}
/// <Summary>
/// Download network resources (supports resumable upload)
/// </Summary>
/// <Param name = "url"> </param>
/// <Param name = "path"> </param>
Public static void simpledownload (string URL, string path)
{
Httpwebrequest request = httpclient. getwebrequest (URL, 0 );

Webresponse response = NULL;

Filestream writer = new filestream (path, filemode. openorcreate, fileaccess. Write );
Long lstartpos = writer. length; // current file size
Long currentlength = 0;
Long totallength = 0; // total size

If (file. exists (PATH) // resumable upload
{
Response = request. getresponse ();
Long stotal = response. contentlength;

If (stotal = lstartpos ){

Close (writer );
File. Move (path, path. Replace (persist_exp ,""));
Print ("Download complete! ");
Return;

}
Request = httpclient. getwebrequest (URL, (INT) lstartpos); // set the range value

Writer. Seek (lstartpos, seekorigin. Begin); // pointer jump
Response = request. getresponse ();

Totallength = response. contentlength + lstartpos; // The total length.
Currentlength = lstartpos; // current length
}
Else
{
Response = request. getresponse ();
Totallength = response. contentlength;
}

Stream reader = response. getresponsestream ();

Byte [] buff = new byte [1024];
Int C = 0; // the actual number of bytes read

While (C = reader. Read (buff, 0, Buff. Length)> 0)
{
Currentlength + = C;
Writer. Write (buff, 0, C );
Progressbar (currentlength, totallength); // progress bar

Writer. Flush ();
}
Close (writer );
If (currentlength = totallength)
{
File. Move (path, path. Replace (persist_exp ,""));
Print ("Download complete! ");
}

If (reader! = NULL)
{
Reader. Close ();
Reader. Dispose ();
Response. Close ();
}
}
Private Static void close (filestream writer)
{
If (writer! = NULL)
{
Writer. Close ();
Writer. Dispose ();
}
}
/// <Summary>
/// Progress bar
/// </Summary>
/// <Param name = "currentlength"> current length </param>
/// <Param name = "totallength"> total length </param>
Public static void progressbar (Object currentlength, object totallength)
{
Double AAA = system. Convert. todouble (currentlength );
Double BBB = system. Convert. todouble (totallength );
Print (currentlength + "/" + totallength + "_" + (AAA/BBB). tostring ("0.00% "));
}
/// <Summary>
/// System output
/// </Summary>
/// <Param name = "OBJ"> </param>
Public static void print (Object OBJ ){
Console. writeline (OBJ );
}
Public static void printstr (string [] Str)
{
Foreach (string D in Str)
{
Print (d );
}
}
/// <Summary>
/// File write
/// </Summary>
/// <Param name = "path"> file path </param>
/// <Param name = "content"> content to be written </param>
Public static void filewriter (string path, string content, encoding)
{
If (file. exists (PATH ))
{
Streamwriter Sw = new streamwriter (path, true, encoding );

Sw. writeline (content );

Sw. Flush ();
Sw. Close ();
}
}
/// <Summary>
/// Read the file and return the content
/// </Summary>
/// <Param name = "path"> file path </param>
/// <Param name = "encoding"> default encoding format </param>
/// <Returns> </returns>
Public static string filereader (string path, encoding ){
Stringbuilder sb = new stringbuilder ();
If (encoding = NULL ){
Encoding = encoding. default;
}
// Read the file
Streamreader sr = new streamreader (path, encoding );
String S = "";
While (S = Sr. Readline ())! = NULL)
{
SB. appendline (s );
}
If (SR! = NULL)
Sr. Close ();

Return sb. tostring ();
}
/// <Summary>
/// Get the file encoding format
/// </Summary>
/// <Param name = "path"> file path </param>
/// <Param name = "defaultencoding"> default encoding </param>
/// <Returns> </returns>
Public static string getfileencoding (string path, string defaultencoding ){
String ED = defaultencoding;
If (file. exists (PATH )){
Filestream FS = new filestream (path, filemode. Open );
Ed = getencoding (FS, defaultencoding );
If (FS! = NULL)
FS. Close ();
}
Return Ed;
}
/// <Summary>
/// Obtain the encoding method of a text file stream.
/// </Summary>
/// <Param name = "stream"> text file stream. </Param>
/// <Param name = "defaultencoding"> default encoding method. If this method cannot obtain a valid leading character from the file header, this encoding method is returned. </Param>
/// <Returns> </returns>
Public static string getencoding (filestream stream, string defaultencoding)
{
String targetencoding = defaultencoding;
If (stream! = NULL & stream. length> = 2)
{
// Save the first 4 bytes of the file stream
Byte byte1 = 0;
Byte byte2 = 0;
Byte byte3 = 0;
Byte byte4 = 0;
// Save the current seek location
Long origpos = stream. Seek (0, seekorigin. Begin );
Stream. Seek (0, seekorigin. Begin );

Int nbyte = stream. readbyte ();
Byte1 = convert. tobyte (nbyte );
Byte2 = convert. tobyte (stream. readbyte ());
If (stream. length> = 3)
{
Byte3 = convert. tobyte (stream. readbyte ());
}
If (stream. length> = 4)
{
Byte4 = convert. tobyte (stream. readbyte ());
}
// Determine Encoding Based on the first four bytes of the file stream
// Unicode {0xff, 0xfe };
// Be-Unicode {0xfe, 0xff };
// Utf8 = {0xef, 0xbb, 0xbf };
If (byte1 = 0xfe & byte2 = 0xff) // unicodebe
{
Targetencoding = encoding. bigendianunicode. bodyname;
}
If (byte1 = 0xff & byte2 = 0xfe & byte3! = 0xff) // Unicode
{
Targetencoding = encoding. Unicode. bodyname;
}
If (byte1 = 0xef & byte2 = 0xbb & byte3 = 0xbf) // utf8
{
Targetencoding = encoding. utf8.bodyname;
}
// Restore the seek location
Stream. Seek (origpos, seekorigin. Begin );
}
Return targetencoding;
}

}
}

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. net;
Using system. net. Security;
Using system. Security. cryptography. x509certificates;
Using system. IO;

Namespace simpledemo
{
/// <Summary>
/// Public HTTP request class
/// </Summary>
Class httpclient
{
/// <Summary>
/// Obtain the basic webrequest
/// </Summary>
/// <Param name = "url"> request address </param>
/// <Param name = "lstartpos"> request start position </param>
/// <Returns> </returns>
Public static httpwebrequest getwebrequest (string URL, int lstartpos)
{
Httpwebrequest request = NULL;
Try
{
Request = (system. net. httpwebrequest) httpwebrequest. Create (URL );
Request. addrange (lstartpos); // sets the range value.
}
Catch (exception ex)
{
Program. Print (ex. Message );
}

Return request;
}
}
}

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.