如何将ArrayList的内容保存到文件中?我正在使用以下代码,但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);
}
答案 0 :(得分:1)
使用序列化可能是个好主意,这个方法会将数组转换为字符串(数组项的类型应该是serialiazable)
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);
}
}
}