1
Friends, by company order, I need to take all the files that a system stores in a Windows directory and store in the Database.
In the database there is a column that stores the directory where the files are, I thought to go through each row of the column that stores the path of the files using Datareader, convert the file to binary and store in the database.
That’s what I got so far, 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();
}
what exactly is your doubt?
– Leandro Angelo
What is the type of column that will store the file in the database?
– Leandro Angelo
I am having the following error: 'There is already an open Datareader associated with this Command that must be closed first' in sqlUpdateCommand.Executenonquery(); which is responsible for updating the field in the table.
– Lucas
Go back to the version of the code you had posted, if you keep editing as the answers may end up confusing the understanding of the original problem and making it difficult for others to help you too.
– Leandro Angelo