Reputation: 385
I'm having a problem with a basic piece of code:
var objReader = new StreamReader(ofDialog.FileName);
while (objReader.Peek() >= 0)
{
Helpers.returnMessage(objReader.ReadLine());
// trim the url to root
var uri = new Uri(objReader.ReadLine());
var host = uri.Host;
}
I'm loading a .txt file of urls, the trying to trim to root using uri.host but i'm getting the error:
Value cannot be null.Parameter name: UriString
But if i hard code a url in: var uri = new Uri("https://stackoverflow.com/questions/ask");
It works fine, it seems to be when i'm loading from a .txt file.
any help would be appreciated.
Complete code:
private void btnInput_Click(object sender, EventArgs e)
{
// ofDialog settings
ofDialog.Filter = @"TXT Files|*.txt";
ofDialog.Title = @"Select your source backlink file...";
ofDialog.FileName = "URLs.txt";
// is cancel pressed?
if (ofDialog.ShowDialog() == DialogResult.Cancel)
return;
try
{
var objReader = new StreamReader(ofDialog.FileName);
while (objReader.Peek() >= 0)
{
//Helpers.returnMessage(objReader.ReadLine());
// trim the url to root
var x = objReader.ReadLine();
Helpers.returnMessage(x);
// trim the url to root
var uri = new Uri(x);
var host = uri.Host;
//Helpers.returnMessage(host);
// extract urls here
var wc = new WebClient();
var html = wc.DownloadString(objReader.ReadLine());
// 1. Find all matches in file
var m1 = Regex.Matches(html, @"(<a.*?>.*?</a>)",
RegexOptions.Singleline);
// 2. Loop over each match
foreach (Match m in m1)
{
var value = m.Groups[1].Value;
string href;
// 3. Get href attribute
var m2 = Regex.Match(value, @"href=\""(.*?)\""",
RegexOptions.Singleline);
if (m2.Success)
{
href = m2.Groups[1].Value;
}
else
{
continue;
}
// add to the results
if (href.StartsWith("http"))
{
//Helpers.returnMessage(href);
if (!href.Contains(host))
{
// add urls to the listview
var lvi = new ListViewItem(href);
listViewMain.Items.Add(lvi);
}
}
}
}
}
catch (Exception ex)
{
Helpers.returnMessage(ex.Message);
}
}
returnMessage() literally just returns a message box popup.
Upvotes: 0
Views: 82
Reputation:
Try this:
var objReader = new StreamReader(ofDialog.FileName);
while (objReader.Peek() >= 0)
{
string x = objReader.ReadLine();
Helpers.returnMessage(x);
// trim the url to root
var uri = new Uri(x);
var host = uri.Host;
}
Upvotes: 1