[英]Creating and saving files in C#
我需要創建並寫入.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/zh-CN/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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.