I need to extract a ID (int number) from a Url.
Example: http://www.example.com/foo/bar/12345
For this I wrote 4 methods where the first one ReadIDsFromFile()
is called by my constructor and the return value is set to a properties of this class. The methods are called in the order I posted them below.
private List<string> ReadIDsFromFile(string path)
{
// path is the full qualified path to a txt file. C:\text.txt
List<string> TweetIDsList = new List<string>();
string temp = string.Empty;
using (StreamReader sr = new StreamReader(path))
{
while ((temp = sr.ReadLine()) != null)
{
if (ValidateUrl(temp))
{
TweetIDsList.Add(ExtractID(temp));
}
else
{
Logger.Log("Invalid URL: {0}", temp);
}
}
}
return TweetIDsList;
}
private bool ValidateUrl(string url)
{
Uri uriResult;
bool result;
return result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}
private string ExtractID(string url)
{
string id = string.Empty;
char[] urlArray = url.ToCharArray();
int result;
for (int i = urlArray.Length - 1; i >= 0; i--)
{
if (Int32.TryParse(urlArray[i].ToString(), out result))
{
id += result;
}
else
{
break; // break loop. If tryparse fails it means we have reached a character which is not a number, probably a forward slash.
}
}
return ReverseNumber(id);
}
private string ReverseNumber(string id)
{
char[] tempArray = id.ToCharArray();
string result = string.Empty;
for (int i = tempArray.Length -1; i >= 0; i--)
{
result += tempArray[i];
}
return result;
}
My code is working without problems so far but I feel like that it is overly unnecessarily complicated. I am especially concerned about the reversed order of the ID and my attempt to reverse it. Is there a better way?