C# WriteAllBytes not writing array correctly

ActivateD

Expert Member
Joined
Jun 7, 2004
Messages
1,774
Reaction score
420
Location
Johannesburg
Hello guys, I have been teaching myself C# for the past 2 months and I have just gone into Input/Output section of C#. I am busy playing around with WriteAllBytes and the myFile.txt when I open it, it does not have the array I created but some unknown text. What am I doing wrong?

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            byte[] myByteArray = new byte[]
    {
    10,
    20,
    30,
    40,
    50
    };
            File.WriteAllBytes("myfile.txt", myByteArray);
            Console.ReadKey();
        }
    }
}

The result I get in myFile.txt is
Code:
üyM

Will I have to use Type-Conversion to make my array appear in myFile.txt?
 
First, what do you expect to have in the file after it has been written to? Also, I assume that that is simply a snippet of your code?
 
First, what do you expect to have in the file after it has been written to? Also, I assume that that is simply a snippet of your code?

I would like the array to appear in myFile.txt
10,20,30,40,50

Yes that is a snippet. Working on the full project elsewhere
 
I would like the array to appear in myFile.txt
10,20,30,40,50

Yes that is a snippet. Working on the full project elsewhere

You're working with bytes, which is not a string.

This is something that would work better, using bytes:
Code:
   byte[] readBuffer = System.IO.File.ReadAllBytes(@"C:\directory\setup.log");
                string t = System.Text.UTF8Encoding.UTF8.GetString(readBuffer);
Console.Writeline(t); //writes the array as a string to screen
System.IO.File.WriteAllBytes(@"C:\directory\setup-1.log", readBuffer);
The above reads in a text file as a byte array and then writes it to a new file (simple copy function).

You want to use strings to have any legible output, something like this: http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
 
Thank you guys I used TextStreamWriter and it works like a bomb. The reason I used WriteAllBytes was because the book I am studying from used it so did not want to venture off too far from the example. BTW Froot your example worked well.
 
Thank you guys I used TextStreamWriter and it works like a bomb. The reason I used WriteAllBytes was because the book I am studying from used it so did not want to venture off too far from the example. BTW Froot your example worked well.

You sure you followed the book correctly? Cause it would seem that if the book used bytes, they'd need to convert the 10,20,30,40,50 string into a set of bytes first before using the writeallbytes command?

Anyway, you live you learn :)
 
Top
Sign up to the MyBroadband newsletter
X