-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);

Sign up to request clarification or add additional context in comments.

Comments

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 Comments

Why are you creating a new UTF8Encoding each time rather than using Encoding.UTF8?
@JonSkeet - not aware of that let me check on msdn...and will update answer
@PranayRana couldn't you just return Encoding.UTF8.GetBytes(str);? You shouldn't need to copy the encoding to another variable.
@Bridge - ok thanks for the infomation...that can be achievable but is that creates and difference

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.