简体   繁体   English

如何使用C#从SQL检索二进制数据?

[英]How can I retrieve binary data from sql with c#?

I retrieved the data that I saved in a filestream column as an example the below code, and got it into memory stream or byte array. 我以下面的代码为例检索了保存在文件流列中的数据,并将其放入内存流或字节数组中。 How can I open it with its default? 如何使用默认设置打开它?

OS application like opening a photo with photo manager or word document with MS Word ? OS应用程序,例如使用照片管理器打开照片或使用MS Word打开Word文档? Normally I use the Process.Start command but it doesn't work with memorystream or byte array so how can this be done ? 通常我使用Process.Start命令, 但是它不适用于memorystream或byte数组,那么该怎么做?

 public DataTable RetriveFile(int Code)
        {
            mydbms d = new mydbms();
            DataTable dt;


           String com2 = "select * from Matn_Naame where Code=" + Code + ";";
           dt = d.executeselectsql(com2);


            return dt;
        }
{
Letter_Manager L_M = new Letter_Manager();
            Byte[] b;
            DataTable dt = new DataTable();
            dt = L_M.RetriveFile(6);

            b=(Byte[])dt.Rows[0]["fileContent"];
            path = dt.Rows[0]["Path"].ToString();

                 MemoryStream Memory = new MemoryStream(b);
                 Memory.Write(b, 0, b.Length);
//??????????????????**?for open and show file**
}

You will need to save the data to a temporary file. 您将需要将数据保存到一个临时文件中。 A temporary filename is available by calling System.IO.Path.GetTempFileName() . 可以通过调用System.IO.Path.GetTempFileName()获得临时文件名。 You can then simply use a FileStream to save to that path, and as you mentioned, Process.Start to launch the default application. 然后,您可以简单地使用FileStream保存到该路径,并如上所述,使用Process.Start启动默认应用程序。

The easiest way is to use the convenient File.WriteAllBytes method which writes a byte array directly to the file name specified. 最简单的方法是使用便捷的File.WriteAllBytes方法,该方法将字节数组直接写入指定的文件名。

var fileName = Path.ChangeExtension(Path.GetTempFileName(), "txt");
File.WriteAllBytes(fileName, b);
Process.Start(fileName);

Note that in my example I have assumed that you are dealing with plain text data that you wish to open with the default text editor. 请注意,在我的示例中,我假设您正在处理要使用默认文本编辑器打开的纯文本数据。

Windows will not know what application to launch this file unless you give it a meaningful extension. 除非您提供有意义的扩展名,否则Windows将不知道启动该文件的应用程序。 You either have to know the format of the data upfront so you can append the correct extension or you'll need to use a library that can guess what kind of data it is such as the excellent TrID file identification tool. 您或者必须预先知道数据的格式,以便可以附加正确的扩展名,或者需要使用可以猜测数据类型的库,例如出色的TrID文件识别工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM