I have a web form where registered users can and upload files. When the user uploads the file it gets saved. If another file with the exact name is uploaded then the filename gets a time and date stamp to stop overwriting old file. I then store the filename in a database but I can't seem to figure out how will I save the new filename in the database. My code is as follows
if(FileUpload1.HasFile)
{
string dir = "DirectoryPath";
string fileName = Path.Combine(dir, FileUpload1.FileName);
if (!File.Exists(fileName))
{
FileUpload1.SaveAs(fileName);
}
else
{
string newFileName =
Path.Combine(Path.GetDirectoryName(fileName),
string.Concat(Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss"),
Path.GetExtension(fileName)));
FileUpload1.SaveAs(newFileName);
}
}
To Save it in the database
using (SqlConnection connection = new SqlConnection("MyConnectionString"))
{
string myQuery = "INSERT INTO MyTable(FileName) VALUES(@Filename)";
SqlCommand cmd = new SqlCommand(myQuery, connection);
cmd.Parameters.AddWithValue("@Filename"); //What argument would I pass here?
connection.Open();
cmd.ExecuteNonQuery();
}
If I do cmd.Parameters.AddWithValue("@Filename",FileUpload1.FileName); then the original name gets stored in the database even if the same file is uploaded twice. Would I put the parameterised queries within the else block? Thanks in advance for your help


