前言:
winform程序下载功能,想要在下载前获取到文件的大小等信息并展示到界面上,通过查找发现网上有类似的JAVA代码,于是效仿之~
JAVA代码:
/**
* 获取网络文件大小
*/
private static long getFileLength(String downloadUrl) throws IOException{
if(downloadUrl == null || "".equals(downloadUrl)){
return 0L ;
}
URL url = new URL(downloadUrl);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");
return (long) conn.getContentLength();
} catch (IOException e) {
return 0L;
} finally {
conn.disconnect();
}
}
C#代码:
public static string GetInfo(string URL)
{
string Results = "";
long ContentL = 0;
if (URL.ToLower().StartsWith("http://"))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
ContentL = response.ContentLength;
response.Close();
Results += GetSize(ContentL);
}
else if (URL.ToLower().StartsWith("ftp://"))
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(URL);
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.UseBinary = true;
FtpWebResponse response = null;
response = (FtpWebResponse)request.GetResponse();
Stream Fs = response.GetResponseStream();
ContentL = response.ContentLength;
Fs.Close();
response.Close();
Results += GetSize(ContentL);
}
else
{
Results += "无法检测";
}
return Results;
}
//大小转化
public static string GetSize(long L)
{
float result;
string re = "";
if (L >= 1073741824)
{
result = L / 1073741824.00F;
re = "GB";
}
else if (L >= 1048576)
{
result = L / 1048576.00F;
re = "MB";
}
else
{
result = L / 1024.00F;
re = "KB";
}
string File_Size = result.ToString("0.00");
return (File_Size + re);
}
版权声明:本文为l_mloveforever原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。