Creating and saving files in C#

c#, file-io, savefiledialog, wpf

Solution

Note that the `SaveFileDialog` only yields a filename but does not actually save anything.

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 ...
}

Use the filename you are getting from the `SaveFileDialog` and do the following:

File.WriteAllText(filename, contents);

That's all if you intend to write text to the file.

You can also use:

File.WriteAllLines(filename, contentsAsStringArray);

Problem

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension. In plain english I would like to know how to: -Create a .dat file -Write to it -And save the file using `SaveFileDialog` There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn. The following code is what I have at the moment. Basically it opens a `SaveFileDialog` window with a blank `File:` section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations. ``` Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = ""; dlg.DefaultExt = ""; Nullable<bool> result = dlg.ShowDialog(); if (result == true) { string filename = dlg.FileName; } ``` Pages that I've been looking at: -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

Original source