c#将.Xlsx文件写入byte []将其保存到SQL数据库然后检索并再次打开它只是被损坏

时间:2017-04-11 16:08:51

标签: c# excel xlsx

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

我有我目前正在努力工作的代码。我已将其缩小到保存和加载byte []。我似乎无法在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();
        }
    }

提前致谢。

0 个答案:

没有答案