做一个获取网络文件的大小信息的小软件,由于我的电脑上网使用的是HTTP代理,所以FTp部分是不能测试代码的可行性,所以先把代码贴出来:
//输入返回文件信息,包括文件名,格式,大小,以及其他信息
private string GetInfo(string URL) { string Results = ""; string filetype = URL.Substring(URL.LastIndexOf(".") + 1, (URL.Length - URL.LastIndexOf(".") - 1)); Results = "类型:" + filetype.ToUpper(); string filename = URL.Substring(URL.LastIndexOf("/") + 1, (URL.Length - URL.LastIndexOf("/") - 1)); Results += "|名称:" + filename; 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) + "|额外信息:" + response.Server; } 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) + "|额外信息:" + response.WelcomeMessage; } else { Results += "|大小:无法检测"; } return Results; } //大小转化 private 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); }
比如像这样的路径是很容易获取信息的:
http://download.hunantv.com/tv/imgotv_1.0.5.5938.exe
但是对于FTP测试的我没有条件测试。