SaveFileDialog setting default path and file type?

前端 未结 3 1422
遇见更好的自我
遇见更好的自我 2020-12-01 07:36

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

相关标签:
3条回答
  • 2020-12-01 07:50

    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
                }
    
    0 讨论(0)
  • 2020-12-01 08:07

    Environment.GetSystemVariable("%SystemDrive%"); will provide the drive OS installed, and you can set filters to savedialog Obtain file path of C# save dialog box

    0 讨论(0)
  • 2020-12-01 08:09

    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.

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

    2. 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!");
    }
    
    0 讨论(0)
提交回复
热议问题