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

5 Answers 5

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.

15

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

byte[] buffer = Encoding.ASCII.GetBytes(data.ToString()); 
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());
6

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

byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
2

try this:

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.