Ale*_*fie 3 .net c# vb.net httpwebrequest addrange
我正在构建这个类来下载部分/部分/段中的文件.在.NET 4.0中,我可以使用此代码指定要下载的范围
long startPos = int.MaxValue+1;
HttpWebRequest.AddRange(startPos);
Run Code Online (Sandbox Code Playgroud)
它的工作原理是因为AddRange方法存在长时间的重载.
当我查看.NET 3.5版本时,我意识到该AddRange()
方法int
仅允许使用.
可能的解决方法是使用AddRange(string, int)
或AddRange(string, int, int)
方法.由于该类必须在.NET 3.5中工作,我将不得不使用字符串规范,但遗憾的是我似乎无法找到任何示例代码来说明如何在.NET 3.5中使用此过程指定范围.任何人都可以表明如何做到这一点?
谢谢.
更新
正如我写的第一个代码示例所示,我想指定一个类型long
而不是int
.使用type int
允许请求最大2GB的字节范围,但long
允许请求2GB的字节范围.
因此问题是:如何HttpWebRequest
在.NET 3.5中指定2GB或更高的字节范围?
这是Mutant_Fruit从WebRequest.AddRange复制的代码- 文件> 2gb 怎么样?显示如何向HttpWebRequest添加长度超过2GB的范围说明符.
MethodInfo method = typeof(WebHeaderCollection).GetMethod
("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://www.example.com/file.exe");
long start = int32.MaxValue;
long end = int32.MaxValue + 100000;
string key = "Range";
string val = string.Format ("bytes={0}-{1}", start, end);
method.Invoke (request.Headers, new object[] { key, val });
Run Code Online (Sandbox Code Playgroud)
我为它写了这个扩展方法.
#region HttpWebRequest.AddRange(long)
static MethodInfo httpWebRequestAddRangeHelper = typeof(WebHeaderCollection).GetMethod
("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
/// <summary>
/// Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
/// </summary>
/// <param name="request">The <see cref="System.Web.HttpWebRequest"/> to add the range specifier to.</param>
/// <param name="start">The starting or ending point of the range.</param>
public static void AddRange(this HttpWebRequest request, long start) { request.AddRange(start, -1L); }
/// <summary>Adds a byte range header to the request for a specified range.</summary>
/// <param name="request">The <see cref="System.Web.HttpWebRequest"/> to add the range specifier to.</param>
/// <param name="start">The position at which to start sending data.</param>
/// <param name="end">The position at which to stop sending data.</param>
public static void AddRange(this HttpWebRequest request, long start, long end)
{
if (request == null) throw new ArgumentNullException("request");
if (start < 0) throw new ArgumentOutOfRangeException("start", "Starting byte cannot be less than 0.");
if (end < start) end = -1;
string key = "Range";
string val = string.Format("bytes={0}-{1}", start, end == -1 ? "" : end.ToString());
httpWebRequestAddRangeHelper.Invoke(request.Headers, new object[] { key, val });
}
#endregion
Run Code Online (Sandbox Code Playgroud)
上面的扩展方法需要以下using
指令
using System.Reflection;
using System.Net;
Run Code Online (Sandbox Code Playgroud)
并且不需要在.NET 4中使用此扩展方法,因为该AddRange
方法有两个重载,接受int64
(long
)作为参数.