FileStream not working properly

I am trying to read/write files using ReadBytemethod. code is working but I have noticed that they are not available after process.I cant open them.I images not displaying.what am i doing wrong again and again.

 if (openFileDialog1.ShowDialog() == DialogResult.OK) {
     if (saveFileDialog1.ShowDialog() == DialogResult.OK) {
          FileStream fsRead = 
              new FileStream(openFileDialog1.FileName, FileMode.Open);
          FileStream fswrite = 
              new FileStream(saveFileDialog1.FileName, FileMode.Create);

         if (fsRead.Position != fsRead.Length) {
             byte b = (byte)fsRead.ReadByte();
             fswrite.WriteByte(b);
         }      
     }
}
Jon Skeet
people
quotationmark

You're only reading a single byte - I suspect you meant to write a while loop instead of an if statement:

while (fsRead.Position != fsRead.Length) {
   byte b = (byte)fsRead.ReadByte();
   fswrite.WriteByte(b);
}

However, that's still not very efficient. Typically it's better to read and write chunks at a time, using "I can't read any more" to indicate the end of the file:

byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fsRead.Read(buffer, 0, buffer.Length)) > 0) {
    fswrite.Write(buffer, 0, bytesRead);
}

However, you don't really need to do this yourself, as you can use Stream.CopyTo to do it for you:

fsRead.CopyTo(fswrite);

Note that you should also use using statements for your streams, to close them automatically at the end of the statement. I'd also use File.OpenWrite and File.OpenRead rather than calling the FileStream constructor, and just use a Stream variable:

using (Stream read = File.OpenRead(openFileDialog1.FileName),
             write = File.OpenWrite(saveFileDialog1.FileName))
{
    read.CopyTo(write);
}

Or just use File.Copy of course!

people

See more on this question at Stackoverflow