我有一个mongodb集合,我将其序列化为List<BsonDocument>
。
有没有办法使用C#将文档列表保存到文件(最好是人类可读的)?
然后将此文件加载回List?
我使用它来保存Settings集合的副本,以便将其传递给不同的用户。
我无法使用mongodb技术(db.copyDatabase),因为用户不具备该级别的访问权限
答案 0 :(得分:1)
您可以使用ToJson()
您可以使用BsonDocument.Parse()
答案 1 :(得分:0)
根据Reda的回答我写了这个:哪个工作正常
/// <summary>
/// Saves the current Settings collection to a file
/// </summary>
internal void BackupSettings()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "JSON files (*.json)|*.json";
saveFileDialog.InitialDirectory = @"C:\Beam.NET\Settings backups";
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
List<BsonDocument> settingsList = _beamDatabaseClient.GetAllSettings();
using (StreamWriter streamWriter = new StreamWriter(saveFileDialog.FileName, false))
{
foreach (var bsonDocument in settingsList)
{
var json = bsonDocument.ToJson();
streamWriter.WriteLine(json);
}
}
}
catch (Exception)
{
MessageBox.Show("Failed to Backup Settings",
"Critical Warning",
MessageBoxButtons.OK,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign,
true);
}
}
}
/// <summary>
/// Restores the Settings collection from a file
/// </summary>
internal void RestoreSettings()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "JSON files (*.json)|*.json";
openFileDialog.InitialDirectory = @"C:\Beam.NET\Settings backups";
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_beamDatabaseClient.DeleteSettings();
using (StreamReader streamReader = new StreamReader(openFileDialog.FileName))
{
string json;
while((json = streamReader.ReadLine()) != null)
{
var bsonDocument = BsonDocument.Parse(json);
_beamDatabaseClient.WriteBSONRecord(Collections.Settings, bsonDocument);
}
}
}
catch (Exception)
{
MessageBox.Show("Failed to Restore Settings",
"Critical Warning",
MessageBoxButtons.OK,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.RightAlign,
true);
}
}
}
}
我没有包含写入MongoDb和从MongoDb写入的方法,但它们只是简单的读/写