convert to C#

  • Thread starter Thread starter Mike
  • Start date Start date
M

Mike

How can i convert this vb.net code to C#,

Dim queueFile As StreamReader

Try
queueFile = File.OpenText("c:\Queue.txt")
Me.txtQueue.Text = queueFile.ReadToEnd
Catch exc As Exception
MsgBox("File could not be read." + vbCrLf + _
"Please verify file C:\Queue.txt has" + _
"has been created on you computer.")
Finally
If Not queueFile Is Nothing Then
queueFile.Close()
End If
End Try
 
StreamReader queueFile = null;
try
{
queueFile = File.OpenText("c:\\Queue.txt");
this.txtQueue.Text = queueFile.ReadToEnd();
}
catch (Exception exc)
{
MsgBox("File could not be read.\n" +
"Please verify file C:\Queue.txt has been created on you
computer.");
}
finally
{
if (queueFile != null)
queueFile.Close();
}


Regards,

Octavio
 
Here you are :

StreamReader queueFile;
try
{
queueFile = File.OpenText(@"c:\Queue.txt");
this.txtQueue.Text = queueFile.ReadToEnd();
}
catch (Exception exc)
{
MessageBox.Show("File could not be read." + Environment.NewLine +
@"Please verify file C:\Queue.txt has" +
"has been created on you computer.");
}
finally
{
if (queueFile != null)
{
queueFile.Close();
}
}
 
How can i convert this vb.net code to C#,

Dim queueFile As StreamReader

Try
queueFile = File.OpenText("c:\Queue.txt")
Me.txtQueue.Text = queueFile.ReadToEnd
Catch exc As Exception
MsgBox("File could not be read." + vbCrLf + _
"Please verify file C:\Queue.txt has" + _
"has been created on you computer.")
Finally
If Not queueFile Is Nothing Then
queueFile.Close()
End If
End Try

download this:

http://www.tiantian.cn/dotnet/ConvertNet.zip

it contains some VB.NET <==> C# converters.

regards, Robert
 
Instant C# gives:

StreamReader queueFile = null;

try
{
queueFile = File.OpenText("c:\\Queue.txt");
this.txtQueue.Text = queueFile.ReadToEnd();
}
catch (Exception exc)
{
MessageBox.Show("File could not be read." + System.Environment.NewLine
+ "Please verify file C:\\Queue.txt has" + "has been created on you
computer.");
}
finally
{
if (! (queueFile == null))
{
queueFile.Close();
}
}
 
Mike said:
How can i convert this vb.net code to C#,

Dim queueFile As StreamReader

Try
queueFile = File.OpenText("c:\Queue.txt")
Me.txtQueue.Text = queueFile.ReadToEnd
Catch exc As Exception
MsgBox("File could not be read." + vbCrLf + _
"Please verify file C:\Queue.txt has" + _
"has been created on you computer.")
Finally
If Not queueFile Is Nothing Then
queueFile.Close()
End If
End Try

The other posters have given a literal conversion. A more idiomatic C#
version would be:

using (StreamWriter queueFile = File.OpenText(@"c:\Queue.txt"))
{
try
{
this.txtQueue.Text = queueFile.ReadToEnd();
}
catch (Exception e)
{
MessageBox.Show("File could not be read."+ Environment.NewLine+
@"Please verify file C:\Queue.txt has"+
"has been created on you computer.");
}
}

(This actually uses an extra try block, and calls queueFile.Dispose()
rather than queueFile.Close(), but is still easier to use, IMO.)
 
Back
Top