C# string to integer conversion issue
Awhile ago, I started making a program in vb.net. Since then i've lost the code, and started using c#. I have everything converted, except the update system I had gives me "Cannot implicitly convert type 'string' to 'int' streamreader".
Heres the old code:
Try
Dim Build As Integer
Build = 3
Dim url As String
url = "###link###"
Dim request As System.Net.HttpWe开发者_运维技巧bRequest = System.Net.HttpWebRequest.Create(url)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("windows-1252"))
Dim Online As Integer
Online = sr.ReadToEnd()
If Build >= Online Then
Label10.Visible = True
Else
LinkLabel1.Visible = True
End If
Catch ex As Exception
Me.Close()
End Try
Here's the code i converted:
try
{
int Build = 0;
Build = 3;
string url = null;
url = "###link###";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebResponse response = request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("windows-1252"));
int Online = 0;
Online = sr.ReadToEnd();
if (Build >= Online)
{
Label10.Visible = true;
}
else
{
LinkLabel1.Visible = true;
}
}
catch (Exception ex)
{
this.Close();
}
I've been googling for days and have found no similar errors or fixes. Any help is appreciated.
StreamReader.ReadToEnd()
returns a string
, you will have to manually convert it to int
:
Online = Convert.ToInt32(sr.ReadToEnd());
int Online;
string onlineString = sr.ReadToEnd();
Online = int.Parse (onlineString);
There are three built-in ways to convert a string to an integer.
int myInt;
myInt = Convert.ToInt32 (s);
myInt = int.Parse (s); // or Int32.Parse (s); // same thing.
if (int.TryParse (s, out myInt)
Console.WriteLine ("parse successful");
else
Console.WriteLine ("parse failed, but no exception was thrown");
Online = int.Parse(sr.ReadToEnd());
sr.ReadToEnd
returns a string. An integer cannot be converted from a string with a simple cast (apparently VB allows this). Try using int.Parse
instead.
Its better to use TryParse to avoid any format exception s.
Try this:
if(Int32.TryParse(sr.ReadToEnd(), out Online))
{
if (Build >= Online)
{
Label10.Visible = true;
}
else
{
LinkLabel1.Visible = true;
}
}
else
{
LinkLabel1.Visible = true;
}
ReadToEnd returns a string. I'm not sure why you can't simply do:
Online = int.Parse(sr.ReadToEnd());
精彩评论