Hi
I have Pdf files stored in a folder on Server. I want to save their paths in Database.
Thanks
Hi
I have Pdf files stored in a folder on Server. I want to save their paths in Database.
Thanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Amit MohantyRank #112 · 20K reputationPosted May 22, 2023, 5:25 AM EDT
Try this
string folderPath = @"C:\path\to\folder"; // Change the path to your server path string[] filePaths = Directory.GetFiles(folderPath, "*.pdf"); using (SqlConnection sqlConnection = new SqlConnection("YourConnectionString")) { sqlConnection.Open(); foreach (string filePath in filePaths) { SqlCommand sqlCommand = new SqlCommand("INSERT INTO YourTable (FilePath) VALUES (@filePath)", sqlConnection); sqlCommand.Parameters.AddWithValue("@filePath", filePath); sqlCommand.ExecuteNonQuery(); } }Konga MounikaRank #1,571 · 1K reputationPosted May 22, 2023, 7:08 AM EDT
Here are the steps on how to save the paths of your PDF files stored in a folder on Server in a database:
file_path: The path to the PDF file.file_name: The name of the PDF file.using (var connection = new SqlConnection("Data Source=localhost;Initial Catalog=MyDatabase;Integrated Security=True"))
{
connection.Open();
var sql = @"
CREATE TABLE PdfFiles
(
file_path NVARCHAR(255) NOT NULL,
file_name NVARCHAR(255) NOT NULL
);
";
var cmd = new SqlCommand(sql, connection);
cmd.ExecuteNonQuery();
var files = Directory.GetFiles(@"C:\path\to\pdf\files", "*.pdf");
foreach (var file in files)
{
var sql = @"
INSERT INTO PdfFiles (file_path, file_name)
VALUES (@file_path, @file_name);
";
var cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@file_path", file);
cmd.Parameters.AddWithValue("@file_name", Path.GetFileName(file));
cmd.ExecuteNonQuery();
}
connection.Close();
}
Once you have saved the file paths in the database, you can access them by querying the database. For example, you can use the following SQL query to get all of the file paths:
SELECT file_path, file_name
FROM PdfFiles;