我想使用 C# 在 MySQL 中执行大文件的记录。我尝试使用以下代码,但它写入的部分具有缓冲区的大小。当我使用与要写入的文件大小相同的缓冲区时,程序使用的内存会增加很多,导致“系统内存不足”,从而终止我的应用程序。这里的代码根据缓冲区的大小分几个部分写入数据库。我想写整个文件,而不是部分。下面是使用的代码:
发送代码:
OpenFileDialog fileDialog = new OpenFileDialog();
string source;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
source = fileDialog.FileName;
}
else
{
MessageBox.Show("To save a file, we need one first");
return;
}
string destination = @"<file_path>";
string destinationFileName = Path.Combine(destination, "<file_name>");
int chunkSize = 7168 * 1024; // Arbitrary buffer size
using (var sourceStream = File.OpenRead(source))
{
using (var destinationStream = File.OpenWrite(destinationFileName))
{
long fileSize = sourceStream.Length;
byte[] buffer = new byte[chunkSize];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await destinationStream.WriteAsync(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
// Calculate progress
double progress = (double)totalBytesRead / fileSize;
// This method is the one that writes to the database
//InsertFileIntoDatabase(connectionString, "Test", buffer);
// Update ProgressBar
lblGravado.Text = "Progress: " + ((int)(progress * 100)).ToString() + "%";
}
// Show completion message
MessageBox.Show("Transfer completed!");
}
}
在MySQL中执行写入的代码:
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
connection.Open();
using (MySqlCommand command = new MySqlCommand("INSERT INTO files_table (file_name, file_content) VALUES (@name, @content)", connection))
{
command.Parameters.AddWithValue("@name", fileName);
command.Parameters.AddWithValue("@content", fileContent);
command.ExecuteNonQuery();
}
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
return;
}
finally
{
connection.Close();
connection.Dispose();
}
如果您能帮助我解决这个问题,我将不胜感激!
我希望你能解决我面临的这个问题。
我还不能发表评论,但是另一种方法怎么样?
只保存文件信息和文件路径怎么样?
如果您有大量文件,但只有一个包含文件信息的小型数据库
处理备份更容易,迁移也很简单。