Hi! I want get path from database and save file in other directory.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FileDB
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Choose_Click(object sender, EventArgs e)
{
string saveDirectory = @"D:\File\";
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (!Directory.Exists(saveDirectory))
{
Directory.CreateDirectory(saveDirectory);
}
filepath.filename = Path.GetFileName(openFileDialog1.FileName);
filepath.fileSavePath = Path.Combine(saveDirectory, filepath.filename);
File.Copy(openFileDialog1.FileName, filepath.fileSavePath, true);
//insert the file into database
string constr = @"Data Source=localhost;Database=dbFiles; uid=sa; pwd=d-123";
SqlConnection conn = new SqlConnection(constr);
string strQuery = "insert into tblFilesPath(Name, Path) values (@Name, @Path)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filepath.filename;
cmd.Parameters.Add("@Path", SqlDbType.NVarChar).Value = filepath.fileSavePath;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
private void Retrieve_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string destFile = @"D:\Folder\";
if (!Directory.Exists(destFile))
{
Directory.CreateDirectory(destFile);
}
string constr = @"Data Source=localhost;Database=dbFiles; uid=sa; pwd=d-123";
SqlConnection conn = new SqlConnection(constr);
string strQuery = "select Name, Path from tblFilesPath";
SqlCommand cmd = new SqlCommand(strQuery, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
conn.Open();
sda.Fill(dt);
conn.Close();
string sourcepath = dt.Rows[0][0].ToString();
File.Copy(sourcepath, destFile + dt.Rows[0][1].ToString(), true);
// MessageBox.Show(dt.Rows[0][1].ToString());
}
public static class filepath
{
public static string fileSavePath;
public static string filename;
}
}
}