0

I'm trying to encrypt a string and write it to a binary file. I want to do the process in reverse. Here is the code I have but it doesn't work.

FileStream stream = new FileStream(saveFileDialog1.OpenFile().ToString(),   FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
String temp = "";
serialList.ForEach(delegate(record p)
{ 
    temp = String.Format("{0},{1}#", p.serial, p.option);
    byte[] dataB = System.Text.Encoding.Unicode.GetBytes(String.Format("{0},{1}#", p.serial, p.option));
    byte[] enc = Encrypt(dataB, "gio!");
    writer.Write(enc);
});
writer.Write('1');
writer.Close();
stream.Close();

What is wrong with it??

1
  • @zmbq: Creates an empty file, like the question says. Commented Jun 8, 2012 at 22:31

2 Answers 2

6

SaveFileDialog.OpenFile already returns you Stream object. You don't need strange .ToString() call that may or may not give you file name/complete file path.

Essentially your code creates 2 streams: one at location specified in FileOpenDialog, and another - somewhere at relative path with file name equal to result of "Stream.ToString()". First stream (the one you likely looking at) will be empty, as you are not writing anything to it.

Note: consider using using(...) instead of manual .Close calls as it creates safer code (you'll not leave stream non-disposed in case of an exception).

Sign up to request clarification or add additional context in comments.

Comments

2

Before closing the stream, flush it, like this.

writer.Flush();
writer.Close();

Alternatively, you can set writer.AutoFlush to true before you begin writing, but that may be slightly slower.

2 Comments

+0. Reasonable advice, but no-op: Close performs Flush. Same as calling Dispose with using (which would make for better code in this case).
@AlexeiLevenkov: I wondered about that, but the code given suggests it is not being flushed. Interesting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.