KAKA
KAKA

Reputation: 131

Upload, Retrieve PDF, DOC and images to SQL Server

I have the following code to upload data from anywhere on my computer into a column called Documents with datatype nvarchar(255) in a table in SQL Server as a file path.

How can I load file path to the Document column in a table and retrieve it when its needed when Open button click? [see screenshot below]

I want to accomplish something like this for each records

Image

On Save button click save to the database file path

Here is the code I am trying to use

List<string> pdfFiles = new List<string>();

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.CheckFileExists = true;
    openFileDialog.AddExtension = true;
    openFileDialog.Multiselect = true;
    openFileDialog.Filter = "PDF files (*.pdf)|*.pdf";

    if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        pdfFiles = new List<string>();

        foreach (string fileName in openFileDialog.FileNames)
            pdfFiles.Add(fileName);
    }
}

private void button2_Click(object sender, EventArgs e)
{
    string installedPath = Application.StartupPath + "pdf";

    // Check whether folder path is exist
    if (!System.IO.Directory.Exists(installedPath))
    {
        // If not create new folder
        System.IO.Directory.CreateDirectory(installedPath);
    }

    // Save pdf files in installedPath
    foreach (string sourceFileName in pdfFiles)
    {
        string destinationFileName = System.IO.Path.Combine(installedPath, System.IO.Path.GetFileName(sourceFileName));
        System.IO.File.Copy(sourceFileName, destinationFileName);
    }
}

Upvotes: 1

Views: 6488

Answers (1)

Shane Ray
Shane Ray

Reputation: 1479

If you are wanting to store a PDF file content to the SQL database navchar(255) is not a good solution. You should read up on the varbinary data type.

This link should give you some clue on where to start: http://www.c-sharpcorner.com/uploadfile/a20beb/how-to-save-pdf-word-and-excel-files-into-the-database/

Upvotes: 1

Related Questions