拿来主义( Ctrl+C Ctrl+V),觉得有用点赞一下
第一步:读取数据
string sql = "select * from FS_UpLoadFile where ID=@ID";
string srConn= "Data Source=.;Initial Catalog=ceshi;User ID=sa;Password=sa.";
SqlConnection Conn = new SqlConnection(srConn);
Conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(sql, Conn);
sda.SelectCommand.Parameters.AddWithValue("@ID", dataGridView1.Rows[e.RowIndex].Cells["ID"].Value);
sda.Fill(dt);
byte[] newbyte = (byte[])dt.Rows[0]["UpLoad_Content"];
string path = "C:\\Users\\Administrator\\Desktop"+ "\\"+dt.Rows[0]["Name"];
第二步;处理从数据库里面读取到的文件名称
//FileInfo通过路径 来处理路径信息
FileInfo f = new FileInfo(path);
//数据库路径: C:\Users\Administrator\Desktop\新建 Microsoft Word 文档.docx
string newPath = f.FullName;
//文件名称 新建: Microsoft Word 文档.docx
string newName = f.Name;
// 文件名不带扩展名: 新建 Microsoft Word 文档
string budaihouzhui = Path.GetFileNameWithoutExtension(f.FullName);
// 获取扩展名: .docx
string houzhui = Path.GetExtension(f.FullName);
// 获取文件的上级目录路径
string DeskTopUrl = f.Directory.FullName;
第三步:处理重复下载
int counter = 1;
while (File.Exists(newPath)) //如果文件存在,如果存在count+1,继续循环
{
newName = string.Format("{0}({1}){2}", budaihouzhui, counter, houzhui); //文件名+(count)+后缀
newPath = Path.Combine(DeskTopUrl, newName); //保存路径
counter++; //count+1
}
第四步:写入
BinaryWriter bw = new BinaryWriter(File.Create(newPath));
bw.Write(newbyte);
bw.Close();
全部代码:
string sql = "select * from FS_UpLoadFile where ID=@ID";
string srConn= "Data Source=.;Initial Catalog=ceshi;User ID=sa;Password=sa.";
SqlConnection Conn = new SqlConnection(srConn);
Conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(sql, Conn);
sda.SelectCommand.Parameters.AddWithValue("@ID", dataGridView1.Rows[e.RowIndex].Cells["ID"].Value);
sda.Fill(dt);
byte[] newbyte = (byte[])dt.Rows[0]["UpLoad_Content"];
string path = "C:\\Users\\Administrator\\Desktop"+ "\\"+dt.Rows[0]["Name"];
//FileInfo通过路径 来处理路径信息
FileInfo f = new FileInfo(path);
//数据库路径: C:\Users\Administrator\Desktop\新建 Microsoft Word 文档.docx
string newPath = f.FullName;
//文件名称 新建: Microsoft Word 文档.docx
string newName = f.Name;
// 文件名不带扩展名: 新建 Microsoft Word 文档
string budaihouzhui = Path.GetFileNameWithoutExtension(f.FullName);
// 获取扩展名: .docx
string houzhui = Path.GetExtension(f.FullName);
// 获取文件的上级目录路径
string DeskTopUrl = f.Directory.FullName;
int counter = 1;
while (File.Exists(newPath)) //如果文件存在,如果存在count+1,继续循环
{
newName = string.Format("{0}({1}){2}", budaihouzhui, counter, houzhui); //文件名+(count)+后缀
newPath = Path.Combine(DeskTopUrl, newName); //保存路径
counter++; //count+1
}
BinaryWriter bw = new BinaryWriter(File.Create(newPath));
bw.Write(newbyte);
bw.Close();
附赠表:
对于每个过滤选项,过滤器字符串均包含过滤器的说明,后跟竖线(|)和过滤器图案。不同过滤选项的字符串由竖线分隔。
以下是过滤器字符串的示例:
Text files (.txt)|.txt|All files (.)|.
您可以通过使用分号分隔文件类型来向过滤器添加多个过滤器模式,例如:
Image Files(.BMP;.JPG;.GIF)|.BMP;.JPG;.GIF|All files (.)|.