在C#中创建和保存文件

问题描述 投票:1回答:2

我需要创建并写入.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://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file

-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx

c# wpf file-io savefiledialog
2个回答
7
投票

请注意,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);

0
投票
using(StreamWriter writer = new StreamWriter(filename , true))
{
  writer.WriteLine("whatever your text is");
}
© www.soinside.com 2019 - 2024. All rights reserved.