I'm using SaveFileDialog.SaveFile
. How can I get it to the default (operating system) drive letter and also limit the options to show only .BIN
as the file extension?
I tried reading the docs on MSDN but I'm very new to this and to be honest I find them sometimes unclear.
To save a file using the SaveFileDialog component. Display the Save File dialog box and call a method to save the file selected by the user. Use the SaveFileDialog component's OpenFile method to save the file. This method gives you a Stream object you can write to.
The SaveFileDialog control prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data. The SaveFileDialog control class inherits from the abstract class FileDialog.
The SaveFileDialog class defined in Microsoft. Win32 namespace represents Windows Save File Dialog control. The following code snippet creates a SaveFileDialog, sets its default extension and fiter properties and calls ShowDialog method that displays SaveFileDialog control.
The SaveFileDialog
control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.
Set the property InitialDirectory
to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.
That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).
Just as a quick example (there are alternative ways to do it).
savefile
is a control of type SaveFileDialog
SaveFileDialog savefile = new SaveFileDialog();
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName))
sw.WriteLine ("Hello World!");
}
Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box
Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):
var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
{
DefaultExt = "*.xml",
Filter = "BIN Files (*.bin)|*.bin",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
};
var result = saveFileDialog.ShowDialog();
if (result != null && result == true)
{
// Save the file here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With