I solved the problem. it must be like this :
int baslangic = Kodlar.IndexOf("<img src=") + 3;
int bitis = Kodlar.Substring(baslangic).IndexOf(">");
I'm trying to parse html with streamreader.
My purpose is , get all images links.
My code is :
string site;
site = $"http://tr.socialll.net/search?name={isim}+{soyad}&location={sehir}&gender=both";
WebRequest talep = HttpWebRequest.Create(site);
WebResponse cevap = talep.GetResponse();
StreamReader oku = new StreamReader(cevap.GetResponseStream());
string Kodlar = oku.ReadToEnd();
int start = Kodlar.IndexOf("<img>") + 4;
int finish = Kodlar.Substring(start).IndexOf("</img>");
Console.WriteLine(Kodlar.Substring(start, finish));
Console.Read();
I want to get here :
<img src="https://iasdai.net/img/user/128x128/116a38953-MWOVJ4aS250K5U.jpg" onerror="this.src='http://tr.socialll.net/img/alternative.png';" alt="">
But i get an error message like this :
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
What should i do?
You could use the HtmlDocument class and get all links by their tags through the predefined method GetElementsByTagName(String)
One problem I spotted was how you are searching for the img element
int start = Kodlar.IndexOf("<img>") + 4;
int finish = Kodlar.Substring(start).IndexOf("</img>");
Compare this to the actual image element, it begins with <img src=" and ends with >. There is no </img> at the end of it, so neither were found and both the start and finish variables were set to -1. Once you tried to use these in your substring commands they threw the out of range error
So what you would probably want to do is adjust your start and finish definitons to something like this:
int start = Kodlar.IndexOf("<img ") + 4;
int finish = Kodlar.Substring(start).IndexOf(">");
You may need to double check the values to verify.
Related
I'm using google finance to convert a currency to another.
The code that I'm using is shown below which was working fine. However, today, I'm facing the IndexOutofrange exception and getting a result of -1 for the indexes searched below (which means that my result does not contain CONVERTED VALUE which is 100% true after logging it.
Then I went to the same web request called, fed it the same parameter, and then inspected the source code from the web browser, and I got the VALUE .
What do you think might be the issue? From a web browser I get the whole result, and from my app the result is missing the converted value field.
private static string CurrencyConvert(decimal amount, string fromCurrency, string toCurrency)
{
try
{
//Grab your values and build your Web Request to the API
string apiURL = String.Format("https://www.google.com/finance/converter?a={0}&from={1}&to={2}&meta={3}", amount, fromCurrency, toCurrency, Guid.NewGuid().ToString());
//Make your Web Request and grab the results
var request = WebRequest.Create(apiURL);
//Get the Response
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);
//Grab your converted value (ie 2.45 USD)
String temp = streamReader.ReadToEnd().ToString();
int pFrom = temp.IndexOf("<span class=bld>") + ("<span class=bld>").Length;
int pTo = temp.LastIndexOf("</span>");
System.Windows.MessageBox.Show(pFrom.ToString() + " " + pTo.ToString());
String result = temp.Substring(pFrom, pTo - pFrom);
// string result = Regex.Matches(streamReader.ReadToEnd(), "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value;
//Get the Result
return result;
}
catch(Exception ex )
{
return "";
}
}
problem with URL. use this one:https://finance.google.com/finance/converter?a={0}&from={1}&to={2}&meta={3}
meta parameter unnecessary
https://finance.google.com/finance/converter?a={0}&from={1}&to={2} works fine as well
I am making a web application.
In main page I want to show some items in Sharepoint List.
So I saved content data(Included text and image source url) and tried to show it.
But I don`t know how to catch image source url.
My Code is Like this.
string itemBody = string.Empty;
//listItemCol is SPListItemCollection
itemBody = listItemCol[i]["Body"] == null ? "" : listItemCol[i]["Body"].ToString();
I checked itemBody, and it contained this data.
<div class="ExternalClass0E1F6FC2B36A47AEB474512CAE7D8B6E">
<p><img alt="group-news__thumb.jpg" src="/SiteAssets/Lists/Announcement/AllItems/group-news__thumb.jpg" style="margin:5px;" /> </p>
<p>News TEST</p>
<p> </p>
</div>
How can I get that image source using c#? Please help me
You can try this.
int stratIndex = itemBody.IndexOf("src=\"");
int endIndex = itemBody.IndexOf("\"", stratIndex + 5);
string result = itemBody.Substring(stratIndex + 5, endIndex - stratIndex - 5);
I had trouble downloading a file from Mediafire. I found out the I have to use their API. I found another SO question: "Get direct download link and file site from Mediafire.com"
With the help of the shown functions I created the following class:
class Program
{
static void Main(string[] args)
{
Mediafireclass mf = new Mediafireclass();
WebClient webClient = new WebClient();
mf.Mediafiredownload("somemediafirelink/test.txt");
webClient.DownloadFileAsync(new Uri("somemediafirelink/test.txt"), #"location to save/test.txt");
}
}
and used the function by T3KBAU5 like this:
internal class Mediafireclass
{
public string Mediafiredownload(string download)
{
HttpWebRequest req;
HttpWebResponse res;
string str = "";
req = (HttpWebRequest)WebRequest.Create(download);
res = (HttpWebResponse)req.GetResponse();
str = new StreamReader(res.GetResponseStream()).ReadToEnd();
int indexurl = str.IndexOf("http://download");
int indexend = GetNextIndexOf('"', str, indexurl);
string direct = str.Substring(indexurl, indexend - indexurl);
return direct;
}
private int GetNextIndexOf(char c, string source, int start)
{
if (start < 0 || start > source.Length - 1)
{
throw new ArgumentOutOfRangeException();
}
for (int i = start; i < source.Length; i++)
{
if (source[i] == c)
{
return i;
}
}
return -1;
}
}
But when I run it this error pops up:
Screenshot of the Error
What can I do to solve the problem, and can you explain what this error means?
Firstly, the Mediafiredownload method returns a string, the direct download link, which you are not using. Your code should resemble:
Mediafireclass mf = new Mediafireclass();
WebClient webClient = new WebClient();
string directLink = mf.Mediafiredownload("somemediafirelink/test.txt");
webClient.DownloadFileAsync(new Uri(directLink), #"location to save/test.txt");
As for the exception it's firing, it's important to understand what the GetNextIndexOf method is doing - iterating through a string, source, to find the index of a character, c, after a certain start position, start. The first line in that method is checking that the start value is within the length of the source string, so that it doesn't immediately look at a character out of the range and throw an ArgumentOutOfRangeException. You need to set a breakpoint on this line:
int indexend = GetNextIndexOf('"', str, indexurl);
And look at the values of str and indexurl using the locals window. This will reveal the problem.
Also, the code you are using is almost 5 years old and I expect this problem is more to do with the fact that Mediafire will have changed the URL structure since then. Your code relies on the fact that the url contains "http://download" which may not be the case any more.
The easiest way is to use an dll file. Such as DirektDownloadLinkCatcher.
Or u have to query for the right div by the "download_link" class and the get the href of the containing tag. Thats the way how I solved it in these dll.^^
Or use the API from MediaFire.
Hoped I could help.
i have a big problem and i need your help. i'm trying send to url parameters to generate the pdf file with the library winnovative. when trying the first time I have no problems and generates pdf but if I want to get the pdf again this gives me error because the parameters in url they are sent and fail to request and falls when so finally assign to generate the pdf file.
I have attached the code for review:
public override void Pagina_PrimeraCarga(object sender, EventArgs e)
{
string datosRequest = Request.QueryString["DATOS"];
char delimitadores = ';';
string[] datos = datosRequest.Split(delimitadores);
imgBanco.Attributes.Add("ImageUrl", "~/App_Themes/Imagenes/Logo.gif");
System.DateTime fecha = new System.DateTime(2014, 12, 17);
lblDia.Text = Convert.ToString(fecha.Day);
lblMes.Text = Convert.ToString(fecha.Month);
lblAno.Text = Convert.ToString(fecha.Year);
string rutEmpresa = datos[3];
int rut = Convert.ToInt32(rutEmpresa);
string rutRes = rut.ToString("N0", CultureInfo.InvariantCulture).Replace(",", ".");
rutRes = rutRes + "-" + datos[4];
lblOficina.Text = "OFICINA: " + datos[0];
lblNombreTitular.Text = "NOMBRE TITULAR: " + datos[1];
lblRut.Text = "R.U.T.: " + rutRes;
lblDireccion.Text = "DIRECCION: " + datos[2];
lblFono.Text = "FONO: " + datos[5];
}
P.D: my apologies for my bad English but my native language is Spanish
P.D.2: Thanks to everyone who could help me in this case
I think that your problem is that after postBack your query string will be empty. Try this
add hiddenfield
<asp:HiddenField runat="server" ID="hidden1" />
then in your pageLoad
if (!IsPostBack)
{
string datosRequest = Request.QueryString["DATOS"];
if(datosRequest != null)
{
//do something
hidden1.Value = datosRequest ;
}
}
else
{
datosRequest = hidden1.Value;
}
I have solved the problem. I was thinking a bit and detects when passed a second time to obtain the pdf that was creating the cookie to be passed to the other form was created and therefore did not pass the data. for this reason I had to add 2 lines but my code for closing the pdf this server delete the cookie and when consulted again remove the client:
Response.Cookies.Clear ();
myCookie.Expires = DateTime.Now.AddDays (1D);
enter code herehey guys im having trouble with xelement when im trying to open the test page an unhandled exception appears and that because the tag doesn't match the closing in another line i tried to add the closings tag but the error happens before the adding function could work
test page http://densetsu.org/PP2012/benchmark1.html
so is there is a way to pass the tag problems without losing the tag effect
this is the main code:
XElement tree = XElement.Load(toolStripTextBox1.Text);
String s = tree.ToString();
textBox1.Text = String_dealer.addmissing(s);
this is the string changer
public static String addmissing(String txt)
{
if (txt.Contains("<br>") || (txt.Contains("</br>")))
{
txt.Replace("<br>", "<br></br>");
txt.Replace("</br>", "<br></br>");
}
else if (txt.Contains("<hr>") || (txt.Contains("</hr>")))
{
txt.Replace("<hr>", "<hr> </hr>");
txt.Replace("</hr>", "<hr> </hr>");
}
return txt;
}
and the problem text :
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: The 'hr' start tag on line 8 does not match the end tag of 'br'. Line 9, position 10.
using a stream reader from a web request then storing the stream into an String file after that you can pass the string to sgml.reader which will transform the html into valid xml