2012-04-21 4 views

답변

2

먼저 데이터베이스의 테이블에 varbinary (MAX) 유형의 열이 있어야합니다. 바이트 배열을 저장할 수 있습니다.

다음으로 바이트 배열로 PDF 파일의 내용을 얻기 위해 코드의 같은 라인을 사용할 수 있습니다

IO.File.ReadAllBytes("C:\my.pdf") 
+2

ntext, text 및 ** image ** 데이터 유형은 이후 버전의 Microsoft SQL Server에서 제거됩니다. 새로운 개발 작업에서는 이러한 데이터 유형을 사용하지 말고 현재 사용중인 응용 프로그램을 수정하십시오. 대신에 nvarchar (max), varchar (max) 및 varbinary (max)를 사용하십시오. '[(source)] (http://msdn.microsoft.com/en-us/library/ms187993.aspx) –

+0

그런 다음 varbinary MAX). MAX는 2^31-1 바이트까지 사용할 수 있기 때문에 MAX는 숫자가 아닌 MAX를 지정하십시오. – Dima

5

당신을 감사합니다! 내 솔루션의 현재 버전은 다음과 같습니다.

public void SaveFile() 
{ 
    //Try 
    OpenFileDialog fd = new OpenFileDialog(); 
    fd.Filter = "pdf file|*.pdf"; 
    if (fd.ShowDialog == System.Windows.Forms.DialogResult.OK) { 
     //PdfDocument1.FilePath = fd.FileName 


     byte[] filebyte = null; 
     SqlConnection con = new SqlConnection("Data Source=LOCALHOS-A4AE79\\LOCALHOST1;Initial Catalog=library_alborz;Integrated Security=True"); 


     SqlCommand cmd = default(SqlCommand); 

     filebyte = System.IO.File.ReadAllBytes(fd.FileName); 


     cmd = new SqlCommand("Insert into pdftbl (pdffld) Values(@pdf)", con); 
     //cmd.Parameters.Add("@filepath", SqlType.VarChar).Value = txtfilepath.Text 
     cmd.Parameters.Add("@pdf", SqlDbType.Binary).Value = filebyte; 
     con.Open(); 
     cmd.ExecuteNonQuery(); 
     con.Close(); 
     Interaction.MsgBox("File saved into database", MsgBoxStyle.Information); 
     //Catch ex As Exception 
     // MsgBox(Err.Description, MsgBoxStyle.Exclamation) 
     //End Try 

    } 
} 


------------ 
// load pdf file 

private void Button2_Click(System.Object sender, System.EventArgs e) 
{ 
    string strsql = null; 
    SqlConnection con = new SqlConnection("Data Source=LOCALHOS-A4AE79\\LOCALHOST1;Initial Catalog=library_alborz;Integrated Security=True"); 
    SqlDataAdapter da = new SqlDataAdapter(); 
    DataSet ds = new DataSet(); 

    try { 
     strsql = "select pdffld from pdftbl "; 
     da = new SqlDataAdapter(strsql, con); 
     da.Fill(ds, "tbl"); 

     //Get image data from gridview column. 
     byte[] pdfData = Convert.ToByte(ds.Tables["tbl"].Rows[0][0]); 

     //Initialize pdf variable 

     //Read pdf data into a memory stream 
     using (MemoryStream ms = new MemoryStream(pdfData, 0, pdfData.Length)) { 
      ms.Write(pdfData, 0, pdfData.Length); 

      //Set pdf variable value using memory stream. 
      PdfDocument1.Load(ms); 
      PdfPageView1.Document = PdfDocument1; 
      PdfPageView1.Refresh(); 

     } 


    } catch (Exception ex) { 
     MessageBox.Show(ex.ToString()); 
    } 
} 
관련 문제