Friends, by company order, I need to get all the files a system stores in a Windows directory and store it in the Database.
In the database there is a column that stores the directory where the files are, I thought of going through each row of the column that stores the path of the files using the DataReader, convert the file to binary and store it in the database. >
What I have so far is this, but I'm stuck:
static void FileStreamMethod()
{
/*Conecta ao SQL*/
SqlConnection cnnSQL = new SqlConnection(@"Data Source=xxxx; " +
"Initial Catalog=SCF2_HOMOLOG;" +
"User ID=xxxxx;" +
"Password=xxxxx");
SqlCommand sqlCommand = new SqlCommand("SELECT id_DocumentoProcessoCompra, Path_Documento " +
"FROM SCF_DocumentoProcessoCompra", cnnSQL);
try { cnnSQL.Open(); }
catch (SqlException ex) { Console.WriteLine(ex.Message); }
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.HasRows)
{
while (sqlDataReader.Read())
{
try
{
string path = @"C:\Users\Lucas Garcia\Desktop\AnexoProcesso\" + sqlDataReader.GetString(1);
/* Objeto origem do arquivo */
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
/*Le o binario do arquivo*/
BinaryReader binaryReader = new BinaryReader(fileStream);
byte[] files = binaryReader.ReadBytes(Convert.ToInt32(fileStream.Length));
SqlCommand sqlUpdateCommand = new SqlCommand("UPDATE SCF_DocumentoProcessoCompra " +
"SET Documento = " + files +
"WHERE id_ModeloDocumento = " + sqlDataReader.GetInt32(0), cnnSQL);
sqlUpdateCommand.ExecuteNonQuery();
binaryReader.Close();
fileStream.Close();
Console.WriteLine("ID {1}\nDocumento {0} armazenado no DB", sqlDataReader.GetString(1), sqlDataReader.GetInt32(0));
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
else
{
Console.WriteLine("No rows found.");
}
sqlDataReader.Close();
}