28

I have the following code:

StringBuilder data = new StringBuilder();
for (int i = 0; i < bytes1; i++)
{ 
    data.Append("a"); 
}
byte[] buffer = Encoding.ASCII.GetBytes(data);

But I get this error:

cannot convert from 'System.Text.StringBuilder' to 'char[]'
The best overloaded method match for 'System.Text.Encoding.GetBytes(char[])'
has some invalid arguments
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
R.Vector
  • 1,669
  • 9
  • 33
  • 41

5 Answers5

46

The following code will fix your issue.

StringBuilder data = new StringBuilder();
for (int i = 0; i < bytes1; i++)
{ data.Append("a"); }
byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());

The problem is that you are passing a StringBuilder to the GetBytes function when you need to passing the string result from the StringBuilder.

Scott Smith
  • 1,823
  • 17
  • 15
15

GetBytes doesn't accept a StringBuilder as a parameter. Use a string with data.ToString()

byte[] buffer = Encoding.ASCII.GetBytes(data.ToString()); 
roken
  • 3,946
  • 1
  • 19
  • 32
8

ASCII is not a good encoding choice for text in this century. Web and mobile applications should be at least using UTF-8, and any other type of application that is supposed to work in a globalized business or social networking environment should too.

StringBuilder builder = new StringBuilder();
for (int i = 0; i < iLength; ++ i)
    builder.Append("a");
byte[] bytesFromBuilder = Encoding.UTF8.GetBytes(builder.ToString());
Douglas Daseeco
  • 3,475
  • 21
  • 27
6

Please try this. StringBuilder is object.. from there, you have to get string value as follow.

byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
Thit Lwin Oo
  • 3,388
  • 3
  • 20
  • 23
2

try this:

byte[] buffer = Encoding.ASCII.GetBytes(data.ToString().ToCharArray());
  • 2
    No need to explicitly convert the string to an array, GetBytes() will accept a string. – roken Feb 02 '12 at 03:48