为什么以下代码不起作用(使用 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);
}

最佳答案

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

此外,每当您使用一次性对象时,请使用 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);
        }

关于.net - 在 .NET Windows 窗体中读取和写入字节数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8696324/

10-13 02:38