在.NET Windows窗体中读取和写入字节数组

rob*_*ert 3 .net file-io

为什么以下代码不起作用(使用Word文档和PDF文件测试)?

保存的文件启动正确的应用程序,但它已损坏,无法打开.

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);
}
Run Code Online (Sandbox Code Playgroud)

com*_*ech 7

使用文件字节数组方法可获得更好的结果.

此外,using无论何时使用一次性物体,都要使用.

        byte[] array;
        string filename;

        using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
        {
            if (openFileDialog1.ShowDialog() != DialogResult.OK) 
                return;
            filename = openFileDialog1.FileName;
            array = File.ReadAllBytes(filename);
        }

        using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
        {
            saveFileDialog1.FileName = filename;
            if (DialogResult.OK != saveFileDialog1.ShowDialog()) 
                return;
            File.WriteAllBytes(array);
        }
Run Code Online (Sandbox Code Playgroud)