Код: Выделить всё
public static async Task CreateBackupAsync()
{
// Generate the timestamped backup file name
var timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
var backupFileName = $"backup_{timestamp}.db";
var backupFilePath = Path.Combine("C:\\Backups", backupFileName);
// Ensure the backup directory exists
Directory.CreateDirectory("C:\\Backups");
using (var location = new SqliteConnection($"Data Source={LocalDbPath}"))
using (var destination = new SqliteConnection($"Data Source={backupFilePath}"))
{
await location.OpenAsync();
await destination.OpenAsync();
location.BackupDatabase(destination);
}
return Path.GetFullPath(backupFilePath);
}
public static async Task UploadFileAsync(string filePath)
{
var containerClient = new BlobContainerClient(new Uri(ConnectionString));
var blobClient = containerClient.GetBlobClient($"database/backup/{Path.GetFileName(filePath)}");
try
{
// Upload the file to Azure Blob Storage
await using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
await blobClient.UploadAsync(fs, true);
}
catch (Exception ex)
{
Debug.WriteLine($"Exception: {ex.Message}");
Debug.WriteLine($"Stack Trace: {ex.StackTrace}");
}
}
Код: Выделить всё
var backup = await DatabaseSynchronizer.CreateBackupAsync();
await DatabaseSynchronizer.UploadFileAsync(backup);
Код: Выделить всё
await using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None)
System.IO.IOException: 'Процесс не может получить доступ к файлу 'C: ...\Debug\net8.0-windows10.0.19041.0\backup_20240702114910.db', поскольку он используется другим процессом.'
файл заблокирован, пока я не закрою приложение. Я не могу найти решение. Я обнаружил, что location.BackupDatabase(destination); вызывает этот метод:
Код: Выделить всё
public virtual void BackupDatabase(SqliteConnection destination)
{
BackupDatabase(destination, "main", "main");
}
Код: Выделить всё
public virtual void BackupDatabase(SqliteConnection destination, string destinationName, string sourceName)
{
if (State != ConnectionState.Open)
{
throw new InvalidOperationException(Resources.CallRequiresOpenConnection("BackupDatabase"));
}
if (destination == null)
{
throw new ArgumentNullException("destination");
}
bool flag = false;
if (destination.State != ConnectionState.Open)
{
destination.Open();
flag = true;
}
try
{
using sqlite3_backup sqlite3_backup = raw.sqlite3_backup_init(destination.Handle, destinationName, Handle, sourceName);
if (sqlite3_backup.IsInvalid)
{
SqliteException.ThrowExceptionForRC(raw.sqlite3_errcode(destination.Handle), destination.Handle);
}
SqliteException.ThrowExceptionForRC(raw.sqlite3_backup_step(sqlite3_backup, -1), destination.Handle);
}
finally
{
if (flag)
{
destination.Close();
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... -to-backup