The most elegant way to delete a string element

I am extracting a line from the output file, which will always be either Ok or Err . After that, I pass this result Ok or Err to the Enum property, which is good, everything works, but I'm sure there should be a better way than mine.

Since I extract 3 characters in case Ok selected, I need to remove the third element from Ok ; result.

 string message = File.ReadAllText(@"C:\Temp\SomeReport.txt").Substring(411, 3); if (message == "Ok;") // `;` character should be removed in case that Ok is fetched { message = "Ok"; } 

thanks

+6
source share
4 answers

You can simply use String.Trim() to remove the ';' if its there.

 string message = File.ReadAllText(@"C:\Temp\SomeReport.txt").Substring(411, 3).TrimEnd(';') 

Result:

 "Err" = "Err" "Ok;" = "Ok" 
+3
source

You can simply do this:

 switch (message) { case "Err": SomeProperty = EnumName.Err; break; case "Ok;": SomeProperty = EnumName.Ok; break; default: throw new Exception("Unexpected file contents: " + message); } 

If you don't like this, you can use TryParse after trimming the semicolon:

 EnumName result; if (Enum.TryParse(message.TrimEnd(';'), out result)) SomePropery = result; else throw new Exception("Unexpected file contents: " + message); 
+1
source
  Enum message = Enum.Err; if (Regex.Match(File.ReadAllText(@"C:\Temp\SomeReport.txt"), "(ok.+?){3}", RegexOptions.Singleline).Success) { message = Enum.OK; } 
+1
source

if you have the following listing

 public enum State { Err, OK } 

using cropping, since sa_adam213 said you can convert it to your enum like this:

 string message = File.ReadAllText(@"C:\Temp\SomeReport.txt").Substring(411, 3).TrimEnd(';') State state = (State)Enum.Parse(typeof(State),message); MessageBox.Show(state.ToString()); //should show OK or Err 

and also pass it int:

 int i = (int)state; MessageBox.Show(i.ToString()); //should show 1 or 0 
0
source

All Articles