TOC

This article is currently in the process of being translated into Dutch (~39% done).

Dialogen:

De SaveFileDialog

De SaveFileDialog (bestand opslaan dialoog) laat je selecteren in welke locatie en met welke naam je een bestand wenst op te slagen. Hij werkt en ziet eruit zoals de OpenFileDialog (bestand openen dialoog) welke we in het vorige hoofdstuk gebruikt hebben, met een paar subtiele verschillen. Net zoals de OpenFileDialog is de SaveFileDialog een omslag rond de standaard Windows dialoog, wat betekent dat je gebruikers ongeveer exact hetzelfde zien als ze deze in jouw applicatie openen of in een andere applicatie (bv. Notepad).

Simple SaveFileDialog example

Om te starten, zullen we beginnen met een simpel voorbeeld voor het gebruiken van de SaveFileDialog:

<Window x:Class="WpfTutorialSamples.Dialogs.SaveFileDialogSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SaveFileDialogSample" Height="300" Width="300">
    <DockPanel Margin="10">
        <WrapPanel HorizontalAlignment="Center" DockPanel.Dock="Top" Margin="0,0,0,10">
            <Button Name="btnSaveFile" Click="btnSaveFile_Click">Save file</Button>
        </WrapPanel>
        <TextBox Name="txtEditor" TextWrapping="Wrap" AcceptsReturn="True" ScrollViewer.VerticalScrollBarVisibility="Auto" />
    </DockPanel>
</Window>
using System;
using System.IO;
using System.Windows;
using Microsoft.Win32;

namespace WpfTutorialSamples.Dialogs
{
	public partial class SaveFileDialogSample : Window
	{
		public SaveFileDialogSample()
		{
			InitializeComponent();
		}

		private void btnSaveFile_Click(object sender, RoutedEventArgs e)
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			if(saveFileDialog.ShowDialog() == true)
				File.WriteAllText(saveFileDialog.FileName, txtEditor.Text);
		}
	}
}

Zoals je ziet draait het vooral over het instantiëren van de SaveFileDialog en dan het roepen van de ShowDialog() (toon dialoog) methode. Als hij true (waar) teruggeeft, gebruiken we de FileName (bestandsnaam) eigenschap (welke de beide de bestandslocatie en de bestandsnaam bevat) als het pad naar waar we moeten schrijven.

Als je op de knop save (opslaan) drukt, zou je een dialoog als deze moeten zien, afhangende van welke versie van Windows je gebruikt:

Filter

Zoals je kan zien in het eerste voorbeeld, heb ik manueel een .txt extensie toegevoegd aan mijn gekozen bestandsnaam, namelijk omdat het "Save as type" ("Opslaan als type") keuze vak leeg is. Net zoals voor de OpenFileDialog, is dit vak bediend door de Filter eigenschap en wordt hij ook op exact dezelfde manier gebruikt.

saveFileDialog.Filter = "Text file (*.txt)|*.txt|C# file (*.cs)|*.cs";

Voor meer details over het gebruik van de Filter eigenschap: zie het vorige artikel over de OpenFileDialog, waar hij wordt uitgelegd in detail.

Met een filter zoals hierboven, zal het resulterende SaveFileDialog er zo uitzien:

With that in place, you can write filenames without specifying the extension - it will be taken from the selected file type in the filter combo box instead. This also indicates to the user which file formats your application supports, which is of course important.

Setting the initial directory

The initial directory used by the SaveFileDialog is decided by Windows, but by using the InitialDirectory property, you can override it. You will usually set this value to a user specified directory, the application directory or perhaps just to the directory last used. You can set it to a path in a string format, like this:

saveFileDialog.InitialDirectory = @"c:\temp\";

If you want to use one of the special folders on Windows, e.g. the Desktop, My Documents or the Program Files directory, you have to take special care, since these may vary from each version of Windows and also depend on which user is logged in. The .NET framework can help you though, just use the Environment class and its members for dealing with special folders:

saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

In this case, I get the path for the My Documents folder, but have a look at the SpecialFolder enumeration - it contains values for a lot of interesting paths. For a full list, please see this MSDN article.

Options

Besides the options already mentioned in this article, I want to draw your attention to the following properties, which will help you tailor the SaveFileDialog to your needs:

AddExtension - defaults to true and determines if the SaveFileDialog should automatically append an extension to the filename, if the user omits it. The extension will be based on the selected filter, unless that's not possible, in which case it will fall back to the DefaultExt property (if specified). If you want your application to be able to save files without file extensions, you may have to disable this option.

OverwritePrompt - defaults to true and determines if the SaveFileDialog should ask for a confirmation if the user enters a file name which will result in an existing file being overwritten. You will normally want to leave this option enabled except in very special situations.

Title - you may override this property if you want a custom title on your dialog. It defaults to "Save As" or the localized equivalent and the property is also valid for the OpenFileDialog.

ValidateNames - defaults to true and unless it's disabled, it will ensure that the user enters only valid Windows file names before allowing the user to continue.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!