-3

I was trying to convert string to Byte. The value of the string was updated by reading XML

  string MyValue= Node.Attributes["Value"].Value.ToUpper().ToString(); 
  MyValue = "NETWORK";
  MyObject.MyValue= Convert.ToByte(MyValue);

  Even tried with using Encoding Option 

But I was getting error as "Input string was not in a correct format"

leppie
  • 115,091
  • 17
  • 196
  • 297
channa
  • 215
  • 1
  • 3
  • 10
  • 1
    7 char string will never be fit into one byte – Perfect28 Apr 08 '15 at 13:07
  • 1
    I think you misunderstand how `Convert.ToByte` works. It doesn't do encoding stuff at all. – Soner Gönül Apr 08 '15 at 13:07
  • 2
    Not clear what you are asking. Not clear what you want to do. Not clear what `MyObject` is. – xanatos Apr 08 '15 at 13:07
  • 1
    possible duplicate of [Converting a string to byte-array without using an encoding (byte-by-byte)](http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array-without-using-an-encoding-byte-by-byte) – irreal Apr 08 '15 at 13:07

2 Answers2

1

The ToByte conversion will only convert a string representation of a number into bytes, eg this will work:

var testString = "1";

var result = Convert.ToByte(testString);

but this will not

var testString = "One";

var result = Convert.ToByte(testString);

Try something like this

Encoding.ASCII.GetBytes("NETWORK");
Anthony Joanes
  • 477
  • 4
  • 17
0

Use one of the encodings in System.Text such as ASCII:

        byte[] bytes = System.Text.ASCIIEncoding.Convert("my string");
smremde
  • 1,800
  • 1
  • 13
  • 25