Public static class filesdownload
{
Private Static readonly dictionary <string, string> mimedic = new dictionary <string, string> ();
Static filesdownload ()
{
Mimedic. Add ("text/plain", "TXT ");
Mimedic. Add ("image/JPEG", "jpg ");
Mimedic. Add ("image/GIF", "GIF ");
}
/// <Summary>
/// Download the object to the specified directory and return the path of the object to be downloaded.
/// </Summary>
/// <Param> URL </param>
/// <Param> storage directory. If a file with the same name as the file to be downloaded already exists in the directory, it will be automatically renamed </param>
/// <Returns> path of the file to be downloaded </returns>
Public static string downloadfile (URI Uri, string savepath)
{
Webresponse q = webrequest. Create (URI). getresponse ();
Stream S = Q. getresponsestream ();
VaR B = new binaryreader (s );
String file = createsavepath (savepath, Uri, Q. contenttype );
VaR FS = new filestream (file, filemode. Create, fileaccess. Write );
FS. Write (B. readbytes (INT) Q. contentlength), 0, (INT) Q. contentlength );
FS. Close ();
B. Close ();
S. Close ();
Return file;
}
Private Static string createsavepath (string savecategory, Uri, string contenttype)
{
If (directory. exists (savecategory) = false)
Directory. createdirectory (savecategory );
String EX = getextentname (contenttype );
String up = NULL;
String upne = NULL;
If (URI. localpath = "/")
{
// Handle the situation where the URL is a domain name
Up = upne = URI. Host;
}
Else
{
If (URI. localpath. endswith ("/"))
{
// Process the directory where the URL is
Up = URI. localpath. substring (0, Uri. localpath. Length-1 );
Upne = path. getfilename (up );
}
Else
{
// Process regular URLs
Up = URI. localpath;
Upne = path. getfilenamewithoutextension (up );
}
}
String name = string. isnullorempty (Ex )? Path. getfilename (up): upne + "." + ex;
String fn = path. Combine (savecategory, name );
Int x = 1;
While (file. exists (FN ))
{
Fn = path. Combine (savecategory,
Path. getfilenamewithoutextension (name) + "(" + x ++ ")" + path. getextension (name ));
}
Return FN;
}
Private Static string getextentname (string contenttype)
{
Foreach (string F in mimedic. Keys)
{
If (contenttype. tolower (). indexof (f)> = 0) return mimedic [f];
}
Return NULL;
}
}
The test usage is as follows:
[Testfixture]
Public class filedownloadtests
{
[Test]
[Ignore]
Public void test download ()
{
String d = @ "D: \ mytest \ downloads ";
// First download
Assert. areequal (@ "D: \ mytest \ downloads \ cf697a340f684bc1a9018e98.jpg ",
Filesdownload. downloadfile (New uri ("http://hiphotos.baidu.com/huyangdiy/pic/item/cf697a340f684bc1a9018e98.jpg"), d ));
// For the second download, an object with the same name is automatically renamed.
Assert. areequal (@ "D: \ mytest \ downloads \ cf697a340f684bc1a9018e98(1).jpg ",
Filesdownload. downloadfile (New uri ("http://hiphotos.baidu.com/huyangdiy/pic/item/cf697a340f684bc1a9018e98.jpg"), d ));
}
}