【问题标题】:Convert varbinary back to .txt file将 varbinary 转换回 .txt 文件
【发布时间】:2011-10-18 07:08:11
【问题描述】:

我有一个存储文件的数据库 (SQL 2008)。 这些被保存为 varbinary(max) 类型。

现在我需要再次获取 .txt 文件,这样我就可以像以前使用 StreamReader 一样循环遍历文件的内容。

while ((line = file.ReadLine()) != null)
{
string code = line.Substring(line.Length - 12);
}

但是如何将 varbinary byte[] 转换回普通的 .txt 文件,以便我能够逐行浏览内容。

我发现了一些关于内存流或文件流的想法,但无法让它们发挥作用。

提前致谢!

【问题讨论】:

标签: c# asp.net file varbinary


【解决方案1】:
MemoryStream m = new MemoryStream(byteArrayFromDB);
StreamReader file = new StreamReader(m);
while ((line = file.ReadLine()) != null)
{
string code = line.Substring(line.Length - 12);
}

【讨论】:

  • 嗯,这比我想象的要容易,但对我来说必须让它变得复杂,尽管我注意到在行尾插入了空格,每行之间还有另一个空格。但这很容易解决。谢谢!
【解决方案2】:

试试这个:

System.IO.File.WriteAllBytes("path to save your file", bytes);

【讨论】:

    【解决方案3】:

    cv 是一个 varbinary(max) 字段

    SqlCommand sqlCmd = new SqlCommand("SELECT cv FROM [job].[UserInfo] Where ID = 39 ", conn); 
    SqlDataReader reader = sqlCmd.ExecuteReader(); 
    
    if (reader.Read() != null)
    {
        byte[] buffer = (byte[])reader["cv"];
        File.WriteAllBytes("c:\\cv1.txt", buffer);
    }
    

    【讨论】:

      【解决方案4】:
          static void Main(string[] args)
          {
              GetData();
          }
          public static void GetData()
          {
              SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["main"].ConnectionString);
              conn.Open();
              string query = "SELECT FileStream FROM [EventOne] Where  ID=2";
              SqlCommand cmd = new SqlCommand(query, conn);
      
              DataTable dt = new DataTable();
              dt.Load(cmd.ExecuteReader());
              byte[] buffer = dt.AsEnumerable().Select(c => c.Field<byte[]>("FileStream")).SingleOrDefault();
              File.WriteAllBytes("c:\\FileStream.txt", buffer);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-29
        • 2016-10-02
        • 2015-12-11
        • 2020-01-08
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        相关资源
        最近更新 更多