byte文件的获取函数

来源:互联网 发布:开淘宝店要下载什么软件 编辑:程序博客网 时间:2024/05/29 18:24

函数

 /// <summary>    /// getBinaryFile:返回所给文件路径的字节数组。    /// </summary>    /// <param name="filename"></param>    /// <returns></returns>    public byte[] getBinaryFile(string filename)    {        if (File.Exists(filename))        {            try            {                ///打开现有文件以进行读取。                FileStream s = File.OpenRead(filename);                return ConvertStreamToByteBuffer(s);            }            catch (Exception e)            {                return new byte[0];            }        }        else        {            return new byte[0];        }    } /// <summary>    /// ConvertStreamToByteBuffer:把给定的文件流转换为二进制字节数组。    /// </summary>    /// <param name="theStream"></param>    /// <returns></returns>    public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)    {        int b1;        System.IO.MemoryStream tempStream = new System.IO.MemoryStream();        while ((b1 = theStream.ReadByte()) != -1)        {            tempStream.WriteByte(((byte)b1));        }        return tempStream.ToArray();    }


 

 

使用示例:

 

  

public byte[] DownLoadLexicon(string name, out int version)    {        String lexiconString = "Select max(version) as ver from Lexicon where lexName='" + name + "'";        lexiconDataSet = new DataSet();        lexiconConnection = new SqlConnection();        lexiconSqlDataAdapter = new SqlDataAdapter();        lexiconConnection.ConnectionString =            "Data Source=.//sqlexpress;Initial Catalog=Lexicon;Integrated Security=True";        lexiconConnection.Open();        lexiconSqlDataAdapter.SelectCommand =            new SqlCommand(lexiconString, lexiconConnection);        lexiconSqlDataAdapter.Fill(lexiconDataSet);        lexiconConnection.Close();        version = 0;        foreach (DataRow row in lexiconDataSet.Tables[0].Rows)        {            if (row["ver"].ToString() != null)            {                version = int.Parse(row["ver"].ToString());            }                }        return getBinaryFile(DBPath + name + ".db");     }


 

byte文件获取:

   

   byte[] myByte = myService.DownLoadLexicon(updataName, out a);   int c = myByte.Length;   FileStream sw;   sw = File.Create(path + "//" + updataName + ".db");   sw.Write(myByte, 0, c);