Search code examples
c#binaryreader

C# Binary Reader


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

Solution

  • 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.