C#字符串到整数转换问题

时间:2011-07-15 01:47:15

标签: c# string integer streamreader

前一段时间,我开始在vb.net上制作一个程序。从那以后我丢失了代码,并开始使用c#。 我已经转换了所有内容,除了我给我的更新系统“无法隐式地将类型'字符串'转换为'int'streamreader”。

继承旧代码:

        Try
        Dim Build As Integer
        Build = 3

        Dim url As String
        url = "###link###"
        Dim request As System.Net.HttpWebRequest = 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

这是我转换的代码:

            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();
        }

我已经谷歌搜索了几天,没有发现类似的错误或修复。任何帮助表示赞赏。

6 个答案:

答案 0 :(得分:5)

StreamReader.ReadToEnd()返回string,您必须手动将其转换为int

Online = Convert.ToInt32(sr.ReadToEnd());

答案 1 :(得分:2)

int Online;
string onlineString = sr.ReadToEnd(); 
Online = int.Parse (onlineString);

将字符串转换为整数有三种内置方法。

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");

答案 2 :(得分:1)

  Online = int.Parse(sr.ReadToEnd());

答案 3 :(得分:1)

sr.ReadToEnd返回一个字符串。无法使用简单转换从字符串转换整数(显然VB允许这样)。请尝试使用int.Parse

答案 4 :(得分:1)

最好使用TryParse来避免任何格式异常。

试试这个:

if(Int32.TryParse(sr.ReadToEnd(), out Online))
{
    if (Build >= Online)
        {
                Label10.Visible = true;
        }
        else
        {
                LinkLabel1.Visible = true;
        }
}
else
{
            LinkLabel1.Visible = true;
}

答案 5 :(得分:0)

ReadToEnd返回一个字符串。我不确定你为什么不能这么做:

Online = int.Parse(sr.ReadToEnd());