Click here to Skip to main content
15,888,590 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to add any type of file like Pdf, Excel,Doc etc.. & saved in sql Database...
Posted
Comments
Mehdi Gholam 27-Oct-13 9:03am    
... and where are you stuck?
Brajabas 27-Oct-13 9:07am    
I think you like to save the file in a folder and its url in database

First , you need to add column in your table with varbinary datatype.
Then you have to convert file in byte array

C#
string sPath ="";//your file name goes here
byte[] ydata = null;
FileInfo fInfo = new FileInfo(sPath);
long lNumBytes = fInfo.Length;
 
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
ydata = br.ReadBytes((int)lNumBytes);
return ydata;


You can use this generated byte array as a parameter value in Insert statement.
 
Share this answer
 
You Should save file to Folder and save Url to dataBase.

Here is sample code...

Code To upload Your File to folder

C#
YourFunctionToUploadImage()
{
  //Check FileUpload controll has File Or not
  if (FileUploadControll.HasFile)
  { 
         
         //check if file already Exists in Folder
         if (File.Exists(Server.MapPath("~/Folder_Name/" + FileUploadControll.FileName)))
         {
               lblUploadstatus.Text = "File Already Exists. Rename filename";
         }
         else
         {
               //To Save Image To your Specific Location.
               //srever.mappath takes us to Folder which containing our application
               FileUploadControll.SaveAs(Server.MapPath("~/Folder_Name/" + FileUploadControll.FileName));
               string FileUrl = Server.MapPath("~/Folder_Name/" + FileUploadControll.FileName;
               //Save This Url To your Database.
               lblUploadstatus.Text = "Upload Status : File Uploaded Successfully";
         } 
         
            
   }
   else 
   {
      lblUploadstatus.Text = "Please Select File";
   }
}


Code To Retrive All files form Folder

C#
PageLoadEvent()
{
    //use DirectoryInfo to get all File's Information
    DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Folder_Name/"));
    FileInfo[] fi = dir.GetFiles();
    //Here You Will Get All Files in fi[].
}


Hope This Help
 
Share this answer
 
v3
there is a SQL datatype called varbinary which you can use for storing binary files inside a database.
Please go through this topic from MSDN documentation to customize for your solution.
http://technet.microsoft.com/en-us/library/ms188362.aspx[^]
Hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900