Reputation: 3637
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??
Upvotes: 0
Views: 4027
Reputation: 100527
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).
Upvotes: 6
Reputation: 44316
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.
Upvotes: 2