Вы находитесь на странице: 1из 9

create database ejemplo

go
use ejemplo
go
create table documentos (
docId int identity,
doc varbinary (max) not null,
nombre varchar (100) not null
)
go
--Proc para guardar documentos
create procedure UploadDoc
@doc varbinary (max),
@nombre varchar (100)
as
begin
insert into documentos values(@doc, @nombre)
end
go
Disear el siguiente formulario en el Visual (El openFileDialog tambin)

Bien, para no hacer largo el codigo, desplegamos Tareas del DataGridView y


agregamos un nuevo origen de datos, como se ve en las siguientes imagenes,
luego elegimos el tipo de origen de datos (Base de datos).
Establecemos la conexin, servidor, y base de datos (ejemplo), luego elegimos
los objetos , este caso solo queremos mostrar dos campos (docId y nombre) y
click en finalizar, con eso ya tenemos cargado todo los datos en el DataGridView,
en el Load del formulario se generar el siguiente codigo:
?
1 private void Formulario_Load(object sender, EventArgs e)
2 {
3 // TODO: esta lnea de cdigo carga datos en la tabla 'ejemploDataSet.documentos'
4 this.documentosTableAdapter.Fill(this.ejemploDataSet.documentos);
5 this.txtRuta.Enabled = false;
}
6
En los eventos correspondientes pegar los codigos que a continuacion se
muestran.
?
using System;
1 using System.Collections.Generic;
2 using System.ComponentModel;
3 using System.Data;
4 using System.Drawing;
5 using System.Linq;
using System.Text;
6 using System.Threading.Tasks;
7 using System.Windows.Forms;
8 using System.IO;
9 using System.Data.SqlClient;
namespace WindowsFormsApplication1
10 {
11 public partial class Formulario : Form
12 {
13 SqlConnection conex = new SqlConnection("Integrated security=true;server
14 SqlCommand cmd;
SqlDataAdapter da;
15 DataTable dtb;
16 string ar = "";
17
18 public Formulario()
19 {
InitializeComponent();
20 }
21 private void Formulario_Load(object sender, EventArgs e)
22 {
23 // TODO: esta lnea de cdigo carga datos en la tabla 'ejemploDataS
24 this.documentosTableAdapter.Fill(this.ejemploDataSet.documentos);
this.txtRuta.Enabled = false;
25 }
26
27 private void btnExaminar_Click(object sender, EventArgs e)
28 {
29 this.openFileDialog1.ShowDialog();
ar = this.openFileDialog1.FileName;
30
this.txtRuta.Text =ar;
31 }
32 private void Limpiar() {
33 txtRuta.Clear();
34 txtTitulo.Clear();
}
35 private void btnGuardar_Click(object sender, EventArgs e)
36 {
37 try
38 {
39 if (txtRuta.Text != "" && txtTitulo.Text != "")
{
40 FileStream fs = new FileStream(ar, FileMode.Open);
41 //Creamos un array de bytes para almacenar los datos ledos
42 Byte[] data = new byte[fs.Length];
//Y guardamos los datos en el array data
43 fs.Read(data, 0, Convert.ToInt32(fs.Length));
44 if (conex.State == 0) { conex.Open(); }
45 cmd = new SqlCommand("UploadDoc", conex);
46 cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@doc", SqlDbType.VarBinary).Value = dat
47 cmd.Parameters.Add("@nombre", SqlDbType.VarChar, 100).Value
48 cmd.ExecuteNonQuery();
49 MessageBox.Show("Guardado Correctamente");
50 this.documentosTableAdapter.Fill(this.ejemploDataSet.docume
51 conex.Close();
fs.Close();
52 Limpiar();
53 }
54 else {
55 MessageBox.Show("Adjuntar y escribir Ttulo");
}
56
57
}
58 catch (Exception)
59 {
60 throw;
61 }
}
62 private void btnLeer_Click(object sender, EventArgs e)
63 {
64 try
65 {
66 int i = this.dataGridView1.CurrentRow.Index;
int cod = int.Parse(this.dataGridView1.Rows[i].Cells[0].Value.To
67 cmd = new SqlCommand("select doc from documentos where docId=" +
68 da = new SqlDataAdapter(cmd);
69 dtb = new DataTable();
70 da.Fill(dtb);
DataRow f = dtb.Rows[0];
71 byte[] bits = ((byte[])(f.ItemArray[0]));
72 string sFile = "tmp" + GenerarNombreFichero() + ".doc";
73 FileStream fs = new FileStream(sFile, FileMode.Create);
74 //Y escribimos en disco el array de bytes que conforman
75 //el fichero Word
fs.Write(bits, 0, Convert.ToInt32(bits.Length));
76 fs.Close();
77 System.Diagnostics.Process obj = new System.Diagnostics.Process(
78 obj.StartInfo.FileName = sFile;
79 obj.Start();
}
80
catch (Exception)
81 {
82
83 throw;
84 }
85 }
private string GenerarNombreFichero()
86 {
87 int ultimoTick = 0;
88 while (ultimoTick == Environment.TickCount)
89 {
90 System.Threading.Thread.Sleep(1);
}
91 ultimoTick = Environment.TickCount;
92 return DateTime.Now.ToString("yyyyMMddhhmmss") + "." +
ultimoTick.ToString();
93 }
94
95 }
96 }
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
Guardar Documentos Word en Base de
Datos SQL mediante C#
Guardar documentos Word a una BD SQL Server, mostrarlos y leerlos.
Empezamos ejecutando el siguiente script en SQL Server.
create database DocBD
go
use DocBD
go
create table documentos (
docId int identity,
doc varbinary (max) not null,
nombre varchar (100) not null
)
go
--Procedimiento para guardar documentos
create procedure P_Doc
@doc varbinary (max),
@nombre varchar (100)
as
begin
insert into documentos values(@doc, @nombre)
end
go

Disear el siguiente formulario:

Establecemos la conexin y base de datos (DocDB), este caso solo queremos mostrar dos campos (docId y
nombre) en el DataGridView, en el Load del formulario escribimos el siguiente codigo:

agragamos tambien las librerias para nuestra conexion


using System.data;
using System.data.SqlClient;
nuestra conexion:
static string CadenaConex = @"Data Source=.\SQLEXPRESS;Initial Catalog =DocBD
;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(CadenaConex);
SqlCommand cmd;
SqlDataAdapter da;
DataTable dtb;
string ar = "";
Cargar los documentos en el dataGridView
private void Form1_Load(object sender, EventArgs e)
{
try
{
this.txtRuta.Enabled = false;
txtTitulo.Focus();
cmd = new SqlCommand("select docid,nombre from documentos", cn);
da = new SqlDataAdapter(cmd);
dtb = new DataTable();
da.Fill(dtb);
dataGridView1.DataSource = dtb;
dataGridView1.Columns[1].Width = 250;
cn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
para limpiar los textBox
private void Limpiar()
{
txtRuta.Clear();
txtTitulo.Clear();
}

generamos nuesto fichero


private string GenerarNombreFichero()
{
int ultimoTick = 0;
while (ultimoTick == Environment.TickCount)
{
System.Threading.Thread.Sleep(1);
}
ultimoTick = Environment.TickCount;
return DateTime.Now.ToString("yyyyMMddhhmmss") + "." + ultimoTick.ToString();
}

Buscar los Documentos de nuestro equipo


private void btnBuscar_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Title = "Abrir";
open.Filter = "Archivos Docx(*.docx)|*.docx|Archivos doc(*.doc)|*.doc|Todos los
Archivos(*.*)|*.*";
if (open.ShowDialog() == DialogResult.OK)
{
ar = open.FileName;
this.txtRuta.Text = ar;
txtTitulo.Text = open.SafeFileName;
}
}

Guardar el Documento Selecctionado


private void btnGuardar_Click(object sender, EventArgs e)
{
try
{
if (txtRuta.Text != "" && txtTitulo.Text != "")
{
FileStream fs = new FileStream(ar, FileMode.Open);
//Creamos un array de bytes para almacenar los datos ledos por fs.
Byte[] data = new byte[fs.Length];
//Y guardamos los datos en el array data
fs.Read(data, 0, Convert.ToInt32(fs.Length));
if (cn.State == 0)
{
cn.Open();
}
cmd = new SqlCommand("P_Doc", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@doc", SqlDbType.VarBinary).Value = data;
cmd.Parameters.Add("@nombre", SqlDbType.VarChar, 100).Value =
this.txtTitulo.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Guardado Correctamente");
this.Form1_Load(null, null);
cn.Close();
fs.Close();
Limpiar();
}
else
{
MessageBox.Show("Adjuntar y escribir Ttulo","Error
Guardar",MessageBoxButtons.OK);
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}

Por ultimo Leemos el Documento de nuestra Base de Datos


private void btnLeer_Click(object sender, EventArgs e)
{
try
{
int i = this.dataGridView1.CurrentRow.Index;
int cod = int.Parse(this.dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd = new SqlCommand("select doc from documentos where docId=" + cod + "", cn);
da = new SqlDataAdapter(cmd);
dtb = new DataTable();
da.Fill(dtb);
DataRow f = dtb.Rows[0];
byte[] bits = ((byte[])(f.ItemArray[0]));
string sFile = "tmp" + GenerarNombreFichero() + ".doc";
FileStream fs = new FileStream(sFile, FileMode.Create);
//Y escribimos en disco el array de bytes que conforman el fichero Word
fs.Write(bits, 0, Convert.ToInt32(bits.Length));
fs.Close();
System.Diagnostics.Process obj = new System.Diagnostics.Process();
obj.StartInfo.FileName = sFile;
obj.Start();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}

public static void Guardar(string nombrearchivo, int length, byte[] archivo)


{
using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString()))
{
conn.Open();

string query = @"INSERT INTO Archivos (nombre, length, archivo)


VALUES (@name, @length, @archivo)";

SqlCommand cmd = new SqlCommand(query, conn);

cmd.Parameters.AddWithValue("@name", nombrearchivo);
cmd.Parameters.AddWithValue("@length", length);

SqlParameter archParam = cmd.Parameters.Add("@archivo", SqlDbType.VarBinary);


archParam.Value = archivo;

cmd.ExecuteNonQuery();

Вам также может понравиться