Hi anjanmedicherla,
Above all, you can call the File.Copy method to copy the selected file to the folder you want to store the file. Next, you need to use a insert command to insert a new record which contains the file information to the related table in the database.
This is a sample table which stores the file information:
create table FileStore
(
id bigint primary key,
name varchar(50),
[path] varchar(255)
)
This is a sample code which shows how to copy the file and save recored into database in detail:
public static class FileSaveHelper
{
//The directory where you want to copy the file to.
private const string SAVE_DIR = @"C:\data";
//The connection string of the database.
private const string CONNECTION_STRING = @"Server=stone\instance;Database=pubs;Trusted_Connection=True;";
public static void SaveFile(string filePath)
{
//Copy the selected file to the saved directory.
string fileName = Path.GetFileName(filePath);
string fileNewPath = Path.Combine(SAVE_DIR, fileName);
File.Copy(filePath, fileNewPath);
//Save the file information to the
using(SqlConnection con = new SqlConnection(CONNECTION_STRING))
{
//Get the new id of the file.
int newId = 0;
SqlCommand getIdCommand = new SqlCommand("select max(id) from FileStore;", con);
object result = getIdCommand.ExecuteScalar();
if(result != DBNull.Value)
{
newId = Convert.ToInt32(result);
}
//Insert the file information to the table.
SqlCommand insertCommand = new SqlCommand("insert into FileStore values(@id,@name,@path);");
insertCommand.Parameters.Add("@id", SqlDbType.BigInt);
insertCommand.Parameters.Add("@name", SqlDbType.VarChar,50);
insertCommand.Parameters.Add("@path", SqlDbType.VarChar,255);
insertCommand.Parameters["@id"].Value = newId;
insertCommand.Parameters["@name"].Value = fileName;
insertCommand.Parameters["@path"].Value = fileNewPath;
insertCommand.ExecuteNonQuery();
}
}
}
Let me know if this does not help.
Aland Li
Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.