c#将.Xlsx文件写入字节[]将其保存到SQL数据库,然后检索并再次打开它,这样会导致损坏

c#将.Xlsx文件写入字节[]将其保存到SQL数据库,然后检索并再次打开它,这样会导致损坏,c#,excel,xlsx,C#,Excel,Xlsx,根据标题,我试图将.xlsx文件(以及用户可能上载的任何其他格式)保存和检索到SQL数据库,然后检索它们以在本机应用程序中打开 我有代码,我目前正在努力工作。我已经把范围缩小到保存和加载字节[]。在c#中,我似乎找不到一个好方法来做这件事 下面是我所拥有的,但它刚刚打开文件,我收到一条消息“Excel无法打开文件”Book1.xlsx,“因为文件格式或扩展名无效。请验证文件是否已损坏,以及文件扩展名是否与文件格式匹配。” 注意:下面的代码适用于图像和其他格式 private byte[

根据标题,我试图将.xlsx文件(以及用户可能上载的任何其他格式)保存和检索到SQL数据库,然后检索它们以在本机应用程序中打开

我有代码,我目前正在努力工作。我已经把范围缩小到保存和加载字节[]。在c#中,我似乎找不到一个好方法来做这件事

下面是我所拥有的,但它刚刚打开文件,我收到一条消息“Excel无法打开文件”Book1.xlsx,“因为文件格式或扩展名无效。请验证文件是否已损坏,以及文件扩展名是否与文件格式匹配。”

注意:下面的代码适用于图像和其他格式

     private byte[] _fileArray;
    private static byte[] ReadFully(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }


    public MainWindow()
    {
        InitializeComponent();

        using (Stream stream = File.OpenRead(@"C:\Users\user\Desktop\Book1.xlsx"))
        {
            stream.Seek(0, SeekOrigin.Begin);
            _fileArray = ReadFully(stream);
        }

    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var newFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()));

        string tempFileName = System.IO.Path.Combine(newFolder.FullName, "Book1.xlsx");


        using (FileStream stream = File.Create(tempFileName))
        {
            FileInfo tempFile = new FileInfo(tempFileName) { Attributes = FileAttributes.Temporary /* optimises by holding in memory*/ };

            stream.Write(_fileArray, 0, _fileArray.Length);

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName = tempFileName;
            //proc.StartInfo.Arguments = "";
            proc.Start();
            proc.Close();
        }
    }

提前谢谢。

不确定数据库与您的问题有什么关系,也不确定C#7标签。从您提供的代码来看,最可能的问题是您在尝试将流加载到Excel之前没有关闭流。此外,您可以通过使用
File.ReadAllBytes()
File.writealBytes()
@David来摆脱大多数tat流读写代码。很抱歉,使用了错误的标记,我只是确定它在正确的区域。为了正确打开文件,需要关闭流,这是正确的。我还重写了代码,现在只使用File.ReadAllBytes和File.WriteAllBytes。非常感谢您的回答!