如何将数组列表的内容保存到文件中
本文关键字:存到文件 数组 列表 | 更新日期: 2023-09-27 18:13:41
如何保存数组列表的内容到文件?我正在使用以下代码,但ToString()只显示一个名称。
编辑
还有一件事我忘了提。我将数据加密存储。我唯一有问题的是获得ArrayList的全部内容并将其传递给加密方法。
推荐使用示例。
SaveFile()方法
private void SaveFile()
{
sfdSaveFile.FileName = storedAuth.UserName;
sfdSaveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
sfdSaveFile.RestoreDirectory = true;
sfdSaveFile.Filter = "AES Binary Files (*.abf)|*.sbf|All files (*.*)|*.*";
sfdSaveFile.DefaultExt = ".abf";
sfdSaveFile.FilterIndex = 1;
sfdSaveFile.ShowDialog();
}
保存文件对话框
private void sfdSaveToLocation_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
EncryptDecrypt en = new EncryptDecrypt();
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
// how to save it appropriately?
string encrypted = en.Encrypt(addWindow.addedEntry.ToString(),
storedAuth.UserName, storedAuth.Password);
File.WriteAllText(sfdSaveFile.FileName, encrypted);
}
使用序列化是一个好主意,这个方法将数组转换为字符串(数组项的类型应该是可序列化的)
public string arrayToString(System.Collections.ArrayList ar)
{
StringBuilder sb = new StringBuilder();
System.Xml.XmlWriterSettings st = new System.Xml.XmlWriterSettings();
st.OmitXmlDeclaration = true;
st.Indent = false;
System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(sb, st);
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(ar.GetType());
s.Serialize(w, ar);
w.Close();
return sb.ToString();
}
public static void SaveArraytoFile(System.Collections.ArrayList ar, string fileName)
{
using (System.IO.StreamWriter sw = new StreamWriter(fileName))
{
foreach (var item in ar)
{
sw.WriteLine(item);
}
}
}