在我的 c# 应用程序(.net 4)中,我想以 KB 计算总上传和下载数据大小,以下是代码,问题是'request.contentLength'总是返回-1。是'request.contentLength'(对于上传数据计算)和“response.contentLength”(用于下载数据计算)是计算此数据的正确语句吗?
private string pageFetch(string url,int requestTimeOut)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = requestTimeOut;
if (!Program.proxyType.Equals("None"))
{
int iPortNo = 0;
try
{
iPortNo = Int32.Parse(Program.proxyPort);
}
catch (Exception ex)
{
iPortNo = 0;
}
WebProxy objProxy = new WebProxy(Program.proxyAddress, iPortNo);
if (!Program.proxyUsername.Equals(""))
{
objProxy.Credentials = new NetworkCredential(Program.proxyUsername, Program.proxyPassword);
}
request.Proxy = objProxy;
}
HttpWebResponse response=null;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
}
lock (lockObject)
{
if (response.ContentLength>0)
totalDownload += (response.ContentLength / 1024);
if(request.ContentLength>0)
totalUpload += (request.ContentLength/1024);
Console.WriteLine("Request length**********" + request.ContentLength);
Console.WriteLine("Up=======" + totalUpload + "Down======" + totalDownload);
}
Program.comment("Response Status=" + response.StatusCode);
string output = "";
if (response != null)
{
if (response.StatusCode == HttpStatusCode.OK)
{
// output processing
}
else
{
response.Close();
}
}
Console.WriteLine("Output=" + output);
return output;
}
pageFetch(string url,int requestTimeOut) 方法在 TPL 中运行。