Re: byte[] to string conversion ...



Hi Jamie,

System.Encoding has already the appropriate methods:

public static string ByteArrayToString(byte[] array)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
return Encoding.ASCII.GetString(array);
}

public static byte[] StringToByteArray(string value)
{
if (value == null)
{
throw new ArgumentNullException("array");
}
return Encoding.ASCII.GetBytes(value);
}

Best Regards,

Wiebe Tijsma
http://www.e-office.com

Jamie Risk wrote:
This is the code snippet that I've come up to convert a byte[] to string. Is there a best practiced method for such a conversion?

- Jamie

public static string ByteArrayToString(byte[] array)
{
if (null == array || 0 == array.Length)
{
throw new NullReferenceException();
return null;
}
else
{
Encoding ascii = Encoding.ASCII;
char[] asciiChars =
new char[ascii.GetCharCount(array, 0, array.Length)];
string str = null;

ascii.GetChars(array, 0, array.Length, asciiChars, 0);

foreach (string s in (new string(asciiChars)).Split('\n'))
{
if (str != null) str += Environment.NewLine;
str += s.Trim();
}
return str;
}
}
.



Relevant Pages

  • Re: iterating through an array of Strings
    ... You named this variable an array, but didn't declare it as one. ... public static String[] data; ... String doesn't declare an array of Strings, it declares an array of String. ... you are grabbing array elements. ...
    (comp.lang.java.help)
  • GetFields not working on enum type (anymore)
    ... I have a method that takes a type that relates to an enum and then gets ... GetFields only ever returns a zero length array. ... public static string[] GetEnumDescriptions ... ReturnNames = Temp; ...
    (microsoft.public.dotnet.languages.csharp)
  • Text problem
    ... GetHeaderFromFiles to build up the array. ... LogHead test = new LogHead; ... public static string GetHeaderFromFile ... public static string getDateStart() ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Text problem
    ... That is to read a log file into an> array and provide methods to get a random line. ... > LogHead test = new LogHead; ... > public static string GetHeaderFromFile ... > public static string getDateStart() ...
    (microsoft.public.dotnet.languages.csharp)
  • Impersonate registry user/pwd
    ... Textwise this works ... StrToByteArray(string str) ... public static string ByteArrayToStr ... RegistryKey typeKey = Registry.LocalMachine.OpenSubKey("Software\\XXX ...
    (microsoft.public.dotnet.framework)