Why doesn’t the following code work (tested using Word documents and PDF files)?
The saved file launches the correct application, but it is corrupted and will not open.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() != DialogResult.OK)
return;
string filename = openFileDialog1.FileName;
FileStream stream = File.OpenRead(filename);
byte[] array = new byte[stream.Length];
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = filename;
if (DialogResult.OK != saveFileDialog1.ShowDialog())
return;
FileInfo fi = new FileInfo(saveFileDialog1.FileName);
using (FileStream fs = fi.OpenWrite())
{
fs.Write(array, 0, array.Length);
}
Use the File byte array methods for better results.
Also, utilize
usingwhenever you are working with disposable objects.