压缩文件,然后使用C#保存到数据库 [英] Zip file then save to database using C#
问题描述
:((大家好,
我在逻辑上苦苦挣扎,我已经从数据库中导出了一个csv文件,但是现在我想将该csv文件压缩为zip文件,然后再次将其保存到数据库中.
非常感谢您的帮助.
问候,
A
:( Hi guys,
I''m struggling with logic here I have exported a csv file from database but now I want to take that csv file zip it then save it to a database again.
Your help will be very much appreciated.
Regards,
A
推荐答案
您可以使用以下链接选择所需的zip方法.
使用GZipStream的文件夹拉链:
http://www.eggheadcafe.com/tutorials/aspnet/9ce6c242-c14c-4969-9251-af95e4cf320f/zip--unzip-folders-and-files-with-c.aspx [ http://www.icsharpcode.net/OpenSource/SharpZipLib/? [ ^ ]
在这里,您有一些用于将文件存储到数据库中的代码. (zip或您想要的任何格式)
You can use the following links to select a zip method you like.
Folder zipper using GZipStream:
http://www.eggheadcafe.com/tutorials/aspnet/9ce6c242-c14c-4969-9251-af95e4cf320f/zip--unzip-folders-and-files-with-c.aspx[^]
Or a component like SharpZipLib:
http://www.icsharpcode.net/OpenSource/SharpZipLib/?[^]
Here you have some code for storing a file into a database. (zip or whatever format you want)
try
{
string constr = "SERVER=localhost;DATABASE=master;pwd=sa;uid=sa";
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
string path = @"C:\TEMP\compressed.zip";
byte[] bytearr = File.ReadAllBytes(path);
string query = "Insert into files values(@file1)";
using (SqlCommand com = new SqlCommand(query,con))
{
com.Parameters.Add(new SqlParameter("@file1", bytearr));
com.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw ex;
}
上面的示例现在获取一个文件,并将其作为字节数组存储到表"files"中,但是您可能会注意到,GZipStream将压缩数据存储到一个流中,该流可以很容易地成为内存流而不是文件流.这样可以避免使用临时文件,但是您需要对文件夹拉链代码进行一些更改.
祝你好运!
The example above now takes a file and stores it into the table "files" as bytearray but as you may notice the GZipStream stores the compressed data into a stream that can easily be a memory stream instead of a file stream. This would avoid the use of a temporary file but you would do some changing to the folder zipper code.
Good luck!
这篇关于压缩文件,然后使用C#保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!