мне не разрешают прокомментировать из-за моей низкой репутации, но решение SilentGhosts должно быть намного легче с file.readlines ([sizehint])
редактирование: SilentGhost является правильным, но это должно быть лучше, чем:
s = ""
for i in xrange(100):
s += file.next()
WebRequest следует за перенаправлениями без вмешательства пользователя, поэтому, если перенаправления используют коды состояния 301/302, то будет работать следующее
WebRequest request = WebRequest.Create(destination);
WebResponse response = request.GetResponse();
Console.WriteLine(response.ResponseUri);
. Если перенаправления создаются с использованием метатегов javascript или HTTP-Equiv, вам необходимо проанализировать страницу и ищите тех. Пакет HTML agility, вероятно, лучший способ сделать это.
Чтобы пойти немного дальше, следующий класс - это класс, который вручную разрешает основные коды состояния перенаправления HTTP, создавая историю по ходу
/// <summary>
/// Digs through HTTP redirects until a non-redirected URL is found.
/// </summary>
public class Digger
{
/// <summary>
/// Initializes a new instance of the <see cref="Digger"/> class.
/// </summary>
public Digger() : this(20)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Digger"/> class.
/// </summary>
/// <param name="maximumDepth">The maximum depth of redirects to parse.</param>
public Digger(int maximumDepth)
{
this.MaximumDepth = maximumDepth;
}
/// <summary>
/// Gets the maximum depth of redirects to parse.
/// </summary>
/// <value>The maximum depth of redirects to parse.</value>
public int MaximumDepth
{
get;
private set;
}
/// <summary>
/// Resolves any redirects at the specified URI.
/// </summary>
/// <param name="destination">The initial URI.</param>
/// <returns>The URI after resolving any HTTP redirects.</returns>
public Uri Resolve(Uri destination)
{
List<Uri> redirectHistory = new List<Uri>();
return this.Resolve(destination, redirectHistory);
}
/// <summary>
/// Resolves any redirects at the specified URI.
/// </summary>
/// <param name="destination">The initial URI.</param>
/// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param>
/// <returns>The URI after resolving any HTTP redirects.</returns>
public Uri Resolve(Uri destination, ICollection<Uri> redirectHistory)
{
redirectHistory.Add(destination);
return this.Resolve(destination, this.MaximumDepth, redirectHistory);
}
/// <summary>
/// Resolves any redirects at the specified URI.
/// </summary>
/// <param name="destination">The initial URI.</param>
/// <param name="hopsLeft">The maximum number of redirects left to follow.</param>
/// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param>
/// <returns>The URI after resolving any HTTP redirects.</returns>
private Uri Resolve(Uri destination, int hopsLeft, ICollection<Uri> redirectHistory)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destination);
request.AllowAutoRedirect = false;
request.Method = "HEAD";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Uri resolvedUri;
if (response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.MovedPermanently)
{
if (hopsLeft > 0)
{
Uri redirectUri = new Uri(response.GetResponseHeader("Location"));
if (redirectHistory.Contains(redirectUri))
{
throw new Exception("Recursive redirection found");
}
redirectHistory.Add(redirectUri);
resolvedUri = this.Resolve(redirectUri, hopsLeft - 1, redirectHistory);
}
else
{
throw new Exception("Maximum redirect depth reached");
}
}
else
{
resolvedUri = response.ResponseUri;
}
return resolvedUri;
}
}
Uri MyUrl = Request.UrlReferrer;
Response.Write("Referrer URL Port: " + Server.HtmlEncode(MyUrl.Port.ToString()) + "<br>");
Response.Write("Referrer URL Protocol: " + Server.HtmlEncode(MyUrl.Scheme) + "<br>");
Насколько я понимаю из вашего вопроса, вы можете использовать такой код, чтобы вы могли видеть предыдущий URL-адрес и сохранять его в базе данных с помощью Linq или других методов ADO.NET.
I предположим, что вы знаете, как сохранить запись в базе данных с помощью LINQ. Если вы этого не сделаете, перейдите по этой ссылке: LINQ to SQL - 5-минутный обзор
Надеюсь, это поможет.