Apoorv Apoorv - 8 months ago 39
Vb.net Question

Run time errors in code converted from VB to C#

I have this piece of code in VB

Private Function ReadProfileViewPlotOptions(ByVal SavePath As String) As ProfileViewOptionsType
Dim FileName As String
Dim filenumber As Short
Dim InInt As Integer
FileName = System.IO.Path.Combine(SavePath, "cfgpropt.sys")
If Not System.IO.File.Exists(FileName) Then
With ReadProfileViewPlotOptions
.ViewConcave = CBool(GetSetting(My.Application.Info.Title, "ProfileViewPlotOptions", "ViewConcave", CStr(1)))

I converted it into C# Like this

private static Mold_Power_Suite.Model.FrontEndStructures.PlanViewOptionsType ReadPlanViewPlotOptions(string SavePath)
var title = ((AssemblyTitleAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0]).Title;
Mold_Power_Suite.Model.FrontEndStructures.PlanViewOptionsType functionReturnValue = default(Mold_Power_Suite.Model.FrontEndStructures.PlanViewOptionsType);
string FileName = null;
short filenumber = 0;
int InInt = 0;
FileName = System.IO.Path.Combine(SavePath, "cfgplopt.sys");
if (!System.IO.File.Exists(FileName))
functionReturnValue.ViewConcave = Convert.ToBoolean(Interaction.GetSetting(title, "PlanViewPlotOptions", "ViewConcave", Convert.ToString(1)));

During run-time , my code is breaking at the line

functionReturnValue.ViewConcave =
Convert.ToBoolean(Interaction.GetSetting(title, "PlanViewPlotOptions",
"ViewConcave", Convert.ToString(1)));

The error shown by the compiler is "Format Exception Unhandled" .String was not recognized as a valid Boolean."

Where am I going wrong ?


When the setting is not found GetSetting returns a default value of "1", ie a string containing the value 1. This cannot be converted to a bool via Convert. But as the last parameter of GetSetting must be a string, you could either use

Convert.ToBoolean(Interaction.GetSetting(title, "PlanViewPlotOptions", "ViewConcave", Convert.ToString(true)));

or just

Convert.ToBoolean(Interaction.GetSetting(title, "PlanViewPlotOptions", "ViewConcave", "true"));