0

I'm making an encryption program and need to save the encrypted password to a file using the binary reader and writer. When i try and read the data out all I get is a number. What did I do wrong?

 public static string readData(string fileName)
    {
        string data;

        FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        using (BinaryReader reader = new BinaryReader(fStream))
        {
            data = reader.Read().ToString();
        }

        return data;   
    }

And the writer

 public static void writeData(string fileName, string data)
 {

  using (BinaryWriter writer = new BinaryWriter(File.Open (fileName, FileMode.Create)))
        {
            writer.Write(data);
        }
    }
user3453481
  • 51
  • 1
  • 9
  • 2
    What does the documentation for `BinaryReader.Read()` tell you? – Jon Skeet Apr 13 '14 at 19:48
  • 2
    Please tell me this is a learning exercise and not for use in any type of production system. – Tom Studee Apr 13 '14 at 19:49
  • This is a learning exersize. I'm a hobbyist as well, newer to c#. Please tell me what's so bad about what I coded. @TomStudee – user3453481 Apr 13 '14 at 19:51
  • @user3453481 Nothing bad at all, and no offense. Even most experienced programmers shouldn't be rolling encryption software from scratch. It's a very specialized area. But, learning is always encouraged. – Tom Studee Apr 13 '14 at 19:53
  • Oh ok, and yes I had to look up examples of encryption coding, as the algorithims can get very complex. This is just a quick program I'm making for fun that could hold my passwords and encrypt them. Should I be using a different way to save the data instead of into a binary file? – user3453481 Apr 13 '14 at 19:55
  • If it's an encrypted password (i.e. a series of bytes), then why does your code work with `string`s (series of characters)? – svick Apr 13 '14 at 19:56

2 Answers2

1

Use reader.ReadString() instead.

data = reader.ReadString();

The Read method reads the next character and returns the corresponding integer value of it as you can see in the documentation.basically, you have written a string to your file in binary format, so you need to read it back.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

That is because you are calling the Read method that returns a single integer.¨

You want to do ReadString.

driis
  • 161,458
  • 45
  • 265
  • 341
  • Most likely he doesn't want. After all how fits a string together with reading and writing _binary_ data? – Uwe Keim Apr 13 '14 at 19:54
  • 1
    Well he did say he was writing the password to a file using `WriteString`, so `ReadString` will be fine for reading it back. (I actually started the answer with `ReadBytes`, but then went back and read the question again). – driis Apr 14 '14 at 18:30