如何将字节数组转换为原始文件(提供文件下载)

时间:2011-07-11 10:59:37

标签: asp.net azure-sql-database

我使用Opendialogbox来读取文件。然后将文件存储在byte []数组中。

file - > byte [] byte [] - >存储在varbinary(max)字段中的SQL AZure上。

这是我的代码:

      OpenFileDialog ofd = new OpenFileDialog();
        if ((bool)ofd.ShowDialog())
        {
             FileStream fileStream = ofd.File.OpenRead());

              byte[]  buffer = new byte[fileStream.Length];
               int read = 0;                             
            using (BinaryReader binaryReader = new BinaryReader(fileStream))
            {
                do
                {
                    read = binaryReader.Read(buffer, 0, Convert.ToInt32(fileStream.Length));
                    // Stored the File in byte[] Array buffer
                } while (read > 0);
            }

        }

现在我想将这个字节数组转换为原始文件(如.doc,.txt,jpeg)。我知道要转换哪个文件的扩展名。

SQL AZure ---> byte [] //完成  byte [] --->到原始文件。 //问题

请提供下载文件的解决方案。

3 个答案:

答案 0 :(得分:1)

一种方式 - 不一定是最好的 - 如下:

using (MemoryStream ms = new MemoryStream(theBytes)) 
{
    using (FileStream fs = new FileStream(string.Format("C:\\tempfile.{0}", theExtension))) 
    {
        ms.WriteTo(fs);
    }
}

答案 1 :(得分:0)

namespace FileSaveDialogDemo  
{  

public partial class MainPage : UserControl  
{ 
    #region Fields  
    SaveFileDialog dialog= new SaveFileDialog(); 
    #endregion  

    #region Constructors  
    public MainPage()  
    {  
        InitializeComponent();  
        this.dialog = new SaveFileDialog();  
        try 
        {  
            this.dialog.DefaultExt = ".txt";  
            this.dialog.Filter = "Text Files|*.txt|Log Files|*.log|All Files|*.*";  
            this.dialog.FilterIndex = 2;  
        }  
        catch ( Exception ex )  
        {  
            this.tblError.Text = "Error configuring SaveFileDialog: " + ex.Message;  
        }  
    } 
    #endregion  

    private void btnSaveFile_Click( object sender, RoutedEventArgs e )  
    {  
        bool? dialogResult = this.dialog.ShowDialog();  

        if ( dialogResult == true )  
        {  
            try 
            {  
               byte[] fileBytes; // your varbinary file from database
               using (Stream fs = (Stream)dialog.OpenFile())
                {
                fs.Write(fileBytes, 0, fileBytes.Length);
                fs.Close();
                lblMsg.Content = "File successfully saved!";
               }   

            }  
            catch ( Exception ex )  
            {  
                this.tblError.Text = "Error calling service: " + ex.Message; 
            }  
        }  
    }  // End of Function
 }// End of MainPage class

} 

答案 2 :(得分:0)

看来你遇到的问题可能与保存二进制文件无关;它更可能是一个基本的安全问题。尝试保存到您具有编程写入权限的路径。例如,尝试保存到我的文档目录而不是C:。尝试使用像这样的Environment.SpecialFolder枚举,并附加文件名+扩展名。

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

您还有许多其他方法可以解决此问题,包括以高架模式启动Visual Studio(以管理员身份运行),和/或允许“Everyone”对C:\驱动器进行写入访问。但我不会推荐这些技术;考虑保存到安全设置低于c:\的文件夹,例如My Documents。