我需要创建并写入.dat文件。我猜这与写入.txt文件几乎相同,只是使用不同的扩展名。
用简单的英语我想知道如何:
- 创建.dat文件
- 写到它
- 并使用SaveFileDialog
保存文件
有几页我一直在关注,但我认为我最好的解释将来自这个网站,因为它允许我准确说明我需要学习的内容。
以下代码是我目前所拥有的。基本上它打开一个SaveFileDialog
窗口与空白的File:
部分。映射到文件夹并按保存不会保存任何内容,因为没有使用文件。请帮我用它来将文件保存到不同的位置。
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
我一直关注的页面:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
请注意,SaveFileDialog
只生成文件名,但实际上并没有保存任何内容。
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
使用您从SaveFileDialog
获得的文件名并执行以下操作:
File.WriteAllText(filename, contents);
如果您打算将文本写入文件,那就是全部。
您还可以使用:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}