Reputation: 53
I obtained a byte array using File.ReadAllBytes();
and I converted it into a string (s
).
I converted my byte array to simple string using this code:
string name;
string s;
byte[] bytes;
bytes = File.ReadAllBytes(name);
foreach (byte b in bytes)
{
s = s + b + ".";
}
Now s
is something like "255.0.0.12.100.4.24.40.0.0.200"
. Now I want to convert this string into a file. Using s.Split('.')
I can get all the individual numbers. But how can I copy all the bytes into a file? (reconstruct the original file)
Upvotes: 1
Views: 394
Reputation: 5106
I'm a little confused by your string array being filled with File.ReadAllBytes(), as this returns a byte[] not a string[]. However, that aside and focusing more on your desire to have a string[] converted to a byte[] you could do something like this (assumes your string[] is called 'str'):
byte[] MyByteArray = str.Select(s => Byte.Parse(s)).ToArray();
Upvotes: 1
Reputation: 8551
Assuming that you want to convert each string into a single byte (parse the string), here's a small program that should demonstrate how to do what you're looking for:
void Main()
{
string[] vals = new string[10];
// populate vals...
byte[] bytes = new byte[vals.Length];
int i = 0;
foreach (string s in vals)
{
bytes[i++] = byte.Parse(s);
}
}
Note that there's no error handling here for the case where the string doesn't parse properly into a byte; in that situation you'll get an exception from the byte.Parse
method.
Upvotes: 0