-4

I am writing a simple ftp client with c#.
I am not pro in c#. Is there any way to convert string to byte[] and write it to the socket?
for example for introducing username this is the socket content:

5553455220736f726f7573680d0a

and ASCII equivalent is:

USER soroush

I want a method to convert string. Something like this:

public byte[] getByte(string str)
{
    byte[] ret;
    //some code here
    return ret;
}
3

2 Answers 2

5

Try

byte[] array = Encoding.ASCII.GetBytes(input);

4
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    Encoding encoding = Encoding.UTF8; //or below line
    //System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
    return encoding.GetBytes(str);
}

and

// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
Encoding enc = Encoding.UTF8; //or below line 
//System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);
4
  • 1
    Why are you creating a new UTF8Encoding each time rather than using Encoding.UTF8?
    – Jon Skeet
    Commented Aug 13, 2012 at 7:30
  • @JonSkeet - not aware of that let me check on msdn...and will update answer Commented Aug 13, 2012 at 7:31
  • 1
    @PranayRana couldn't you just return Encoding.UTF8.GetBytes(str);? You shouldn't need to copy the encoding to another variable.
    – Bridge
    Commented Aug 13, 2012 at 7:43
  • @Bridge - ok thanks for the infomation...that can be achievable but is that creates and difference Commented Aug 13, 2012 at 7:44

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