Code:
/ Dotnetfx_Win7_3.5.1 / Dotnetfx_Win7_3.5.1 / 3.5.1 / DEVDIV / depot / DevDiv / releases / whidbey / NetFXspW7 / ndp / fx / src / WinForms / Managed / System / WinForms / SaveFileDialog.cs / 1 / SaveFileDialog.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Diagnostics;
using System;
using CodeAccessPermission = System.Security.CodeAccessPermission;
using System.IO;
using System.Drawing;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.Win32;
///
///
///
/// Represents
/// a common dialog box that allows the user to specify options for saving a
/// file. This class cannot be inherited.
///
///
[
Designer("System.Windows.Forms.Design.SaveFileDialogDesigner, " + AssemblyRef.SystemDesign),
SRDescription(SR.DescriptionSaveFileDialog)
]
public sealed class SaveFileDialog : FileDialog {
///
///
///
/// Gets or sets a value indicating whether the dialog box prompts the user for
/// permission to create a file if the user specifies a file that does not exist.
///
///
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
SRDescription(SR.SaveFileDialogCreatePrompt)
]
public bool CreatePrompt {
get {
return GetOption(NativeMethods.OFN_CREATEPROMPT);
}
set {
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded");
IntSecurity.FileDialogCustomization.Demand();
SetOption(NativeMethods.OFN_CREATEPROMPT, value);
}
}
///
///
///
/// Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies
/// a file name that already exists.
///
///
[
SRCategory(SR.CatBehavior),
DefaultValue(true),
SRDescription(SR.SaveFileDialogOverWritePrompt)
]
public bool OverwritePrompt {
get {
return GetOption(NativeMethods.OFN_OVERWRITEPROMPT);
}
set {
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded");
IntSecurity.FileDialogCustomization.Demand();
SetOption(NativeMethods.OFN_OVERWRITEPROMPT, value);
}
}
///
///
///
/// Opens the file with read/write permission selected by the user.
///
///
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
/// SECREVIEW: ReviewImperativeSecurity
/// vulnerability to watch out for: A method uses imperative security and might be constructing the permission using state information or return values that can change while the demand is active.
/// reason for exclude: filename is a local variable and not subject to race conditions.
[SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
public Stream OpenFile() {
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogSaveFile Demanded");
IntSecurity.FileDialogSaveFile.Demand();
string filename = FileNamesInternal[0];
if (string.IsNullOrEmpty(filename))
throw new ArgumentNullException( "FileName" );
Stream s = null;
// SECREVIEW : We demanded the FileDialog permission above, so it is safe
// : to assert this here. Since the user picked the file, it
// : is OK to give them read/write access to the stream.
//
new FileIOPermission(FileIOPermissionAccess.AllAccess, IntSecurity.UnsafeGetFullPath(filename)).Assert();
try {
s = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
}
finally {
CodeAccessPermission.RevertAssert();
}
return s;
}
///
///
///
/// Prompts the user with a
/// when a file is about to be created. This method is
/// invoked when the CreatePrompt property is true and the specified file
/// does not exist. A return value of false prevents the dialog from
/// closing.
///
///
private bool PromptFileCreate(string fileName)
{
return MessageBoxWithFocusRestore(SR.GetString(SR.FileDialogCreatePrompt, fileName),
DialogCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
}
///
///
///
/// Prompts the user when a file is about to be overwritten. This method is
/// invoked when the "overwritePrompt" property is true and the specified
/// file already exists. A return value of false prevents the dialog from
/// closing.
///
///
///
private bool PromptFileOverwrite(string fileName) {
return MessageBoxWithFocusRestore(SR.GetString(SR.FileDialogOverwritePrompt, fileName),
DialogCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
}
// If it's necessary to throw up a "This file exists, are you sure?" kind of
// MessageBox, here's where we do it.
// Return value is whether or not the user hit "okay".
internal override bool PromptUserIfAppropriate(string fileName) {
if (!base.PromptUserIfAppropriate(fileName)) {
return false;
}
//Note: When we are using the Vista dialog mode we get two prompts (one from us and one from the OS) if we do this
if ((options & NativeMethods.OFN_OVERWRITEPROMPT) != 0 && FileExists(fileName) && !this.UseVistaDialogInternal) {
if (!PromptFileOverwrite(fileName)) {
return false;
}
}
if ((options & NativeMethods.OFN_CREATEPROMPT) != 0 && !FileExists(fileName)) {
if (!PromptFileCreate(fileName)) {
return false;
}
}
return true;
}
///
///
///
/// Resets all dialog box options to their default
/// values.
///
///
public override void Reset() {
base.Reset();
SetOption(NativeMethods.OFN_OVERWRITEPROMPT, true);
}
internal override void EnsureFileDialogPermission()
{
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogSaveFile Demanded in SaveFileDialog.RunFileDialog");
IntSecurity.FileDialogSaveFile.Demand();
}
///
///
///
///
internal override bool RunFileDialog(NativeMethods.OPENFILENAME_I ofn) {
//We have already done the demand in EnsureFileDialogPermission but it doesn't hurt to do it again
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogSaveFile Demanded in SaveFileDialog.RunFileDialog");
IntSecurity.FileDialogSaveFile.Demand();
bool result = UnsafeNativeMethods.GetSaveFileName(ofn);
if (!result) {
// Something may have gone wrong - check for error condition
//
int errorCode = SafeNativeMethods.CommDlgExtendedError();
switch(errorCode) {
case NativeMethods.FNERR_INVALIDFILENAME:
throw new InvalidOperationException(SR.GetString(SR.FileDialogInvalidFileName, FileName));
}
}
return result;
}
internal override string[] ProcessVistaFiles(FileDialogNative.IFileDialog dialog)
{
FileDialogNative.IFileSaveDialog saveDialog = (FileDialogNative.IFileSaveDialog)dialog;
FileDialogNative.IShellItem item;
dialog.GetResult(out item);
return new string[] { GetFilePathFromShellItem(item) };
}
internal override FileDialogNative.IFileDialog CreateVistaDialog()
{ return new FileDialogNative.NativeFileSaveDialog(); }
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//-----------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Diagnostics;
using System;
using CodeAccessPermission = System.Security.CodeAccessPermission;
using System.IO;
using System.Drawing;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.Win32;
///
///
///
/// Represents
/// a common dialog box that allows the user to specify options for saving a
/// file. This class cannot be inherited.
///
///
[
Designer("System.Windows.Forms.Design.SaveFileDialogDesigner, " + AssemblyRef.SystemDesign),
SRDescription(SR.DescriptionSaveFileDialog)
]
public sealed class SaveFileDialog : FileDialog {
///
///
///
/// Gets or sets a value indicating whether the dialog box prompts the user for
/// permission to create a file if the user specifies a file that does not exist.
///
///
[
SRCategory(SR.CatBehavior),
DefaultValue(false),
SRDescription(SR.SaveFileDialogCreatePrompt)
]
public bool CreatePrompt {
get {
return GetOption(NativeMethods.OFN_CREATEPROMPT);
}
set {
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded");
IntSecurity.FileDialogCustomization.Demand();
SetOption(NativeMethods.OFN_CREATEPROMPT, value);
}
}
///
///
///
/// Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies
/// a file name that already exists.
///
///
[
SRCategory(SR.CatBehavior),
DefaultValue(true),
SRDescription(SR.SaveFileDialogOverWritePrompt)
]
public bool OverwritePrompt {
get {
return GetOption(NativeMethods.OFN_OVERWRITEPROMPT);
}
set {
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogCustomization Demanded");
IntSecurity.FileDialogCustomization.Demand();
SetOption(NativeMethods.OFN_OVERWRITEPROMPT, value);
}
}
///
///
///
/// Opens the file with read/write permission selected by the user.
///
///
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
/// SECREVIEW: ReviewImperativeSecurity
/// vulnerability to watch out for: A method uses imperative security and might be constructing the permission using state information or return values that can change while the demand is active.
/// reason for exclude: filename is a local variable and not subject to race conditions.
[SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
public Stream OpenFile() {
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogSaveFile Demanded");
IntSecurity.FileDialogSaveFile.Demand();
string filename = FileNamesInternal[0];
if (string.IsNullOrEmpty(filename))
throw new ArgumentNullException( "FileName" );
Stream s = null;
// SECREVIEW : We demanded the FileDialog permission above, so it is safe
// : to assert this here. Since the user picked the file, it
// : is OK to give them read/write access to the stream.
//
new FileIOPermission(FileIOPermissionAccess.AllAccess, IntSecurity.UnsafeGetFullPath(filename)).Assert();
try {
s = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
}
finally {
CodeAccessPermission.RevertAssert();
}
return s;
}
///
///
///
/// Prompts the user with a
/// when a file is about to be created. This method is
/// invoked when the CreatePrompt property is true and the specified file
/// does not exist. A return value of false prevents the dialog from
/// closing.
///
///
private bool PromptFileCreate(string fileName)
{
return MessageBoxWithFocusRestore(SR.GetString(SR.FileDialogCreatePrompt, fileName),
DialogCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
}
///
///
///
/// Prompts the user when a file is about to be overwritten. This method is
/// invoked when the "overwritePrompt" property is true and the specified
/// file already exists. A return value of false prevents the dialog from
/// closing.
///
///
///
private bool PromptFileOverwrite(string fileName) {
return MessageBoxWithFocusRestore(SR.GetString(SR.FileDialogOverwritePrompt, fileName),
DialogCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
}
// If it's necessary to throw up a "This file exists, are you sure?" kind of
// MessageBox, here's where we do it.
// Return value is whether or not the user hit "okay".
internal override bool PromptUserIfAppropriate(string fileName) {
if (!base.PromptUserIfAppropriate(fileName)) {
return false;
}
//Note: When we are using the Vista dialog mode we get two prompts (one from us and one from the OS) if we do this
if ((options & NativeMethods.OFN_OVERWRITEPROMPT) != 0 && FileExists(fileName) && !this.UseVistaDialogInternal) {
if (!PromptFileOverwrite(fileName)) {
return false;
}
}
if ((options & NativeMethods.OFN_CREATEPROMPT) != 0 && !FileExists(fileName)) {
if (!PromptFileCreate(fileName)) {
return false;
}
}
return true;
}
///
///
///
/// Resets all dialog box options to their default
/// values.
///
///
public override void Reset() {
base.Reset();
SetOption(NativeMethods.OFN_OVERWRITEPROMPT, true);
}
internal override void EnsureFileDialogPermission()
{
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogSaveFile Demanded in SaveFileDialog.RunFileDialog");
IntSecurity.FileDialogSaveFile.Demand();
}
///
///
///
///
internal override bool RunFileDialog(NativeMethods.OPENFILENAME_I ofn) {
//We have already done the demand in EnsureFileDialogPermission but it doesn't hurt to do it again
Debug.WriteLineIf(IntSecurity.SecurityDemand.TraceVerbose, "FileDialogSaveFile Demanded in SaveFileDialog.RunFileDialog");
IntSecurity.FileDialogSaveFile.Demand();
bool result = UnsafeNativeMethods.GetSaveFileName(ofn);
if (!result) {
// Something may have gone wrong - check for error condition
//
int errorCode = SafeNativeMethods.CommDlgExtendedError();
switch(errorCode) {
case NativeMethods.FNERR_INVALIDFILENAME:
throw new InvalidOperationException(SR.GetString(SR.FileDialogInvalidFileName, FileName));
}
}
return result;
}
internal override string[] ProcessVistaFiles(FileDialogNative.IFileDialog dialog)
{
FileDialogNative.IFileSaveDialog saveDialog = (FileDialogNative.IFileSaveDialog)dialog;
FileDialogNative.IShellItem item;
dialog.GetResult(out item);
return new string[] { GetFilePathFromShellItem(item) };
}
internal override FileDialogNative.IFileDialog CreateVistaDialog()
{ return new FileDialogNative.NativeFileSaveDialog(); }
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- AccessedThroughPropertyAttribute.cs
- CryptoStream.cs
- ThumbAutomationPeer.cs
- SiteMap.cs
- SqlConnection.cs
- FrameworkPropertyMetadata.cs
- ConfigurationPermission.cs
- PeerNameRecordCollection.cs
- AutomationProperty.cs
- ReceiveActivityDesigner.cs
- RuleDefinitions.cs
- StrokeNodeOperations.cs
- MemoryMappedView.cs
- LineGeometry.cs
- ReadOnlyNameValueCollection.cs
- VisualBrush.cs
- InvokeHandlers.cs
- UnionCqlBlock.cs
- HttpServerUtilityWrapper.cs
- MarkupObject.cs
- HandleInitializationContext.cs
- SchemaElementLookUpTable.cs
- CodePrimitiveExpression.cs
- ListItemParagraph.cs
- OdbcUtils.cs
- PeerDuplexChannel.cs
- XmlSerializer.cs
- PropertyGeneratedEventArgs.cs
- SafeReversePInvokeHandle.cs
- ExceptionRoutedEventArgs.cs
- DocumentViewerBase.cs
- XpsS0ValidatingLoader.cs
- ClientRoleProvider.cs
- QuotedPrintableStream.cs
- EventsTab.cs
- CompositeCollection.cs
- ObjectSet.cs
- RuntimeResourceSet.cs
- MenuScrollingVisibilityConverter.cs
- WindowsGraphicsWrapper.cs
- EncoderBestFitFallback.cs
- TextTreeUndo.cs
- Function.cs
- SQLBytesStorage.cs
- ThreadStartException.cs
- WeakEventTable.cs
- UserInitiatedRoutedEventPermission.cs
- PageParserFilter.cs
- PaperSize.cs
- ClientSettingsProvider.cs
- RequestCache.cs
- HtmlInputImage.cs
- ExceptionHelpers.cs
- UTF32Encoding.cs
- CanonicalXml.cs
- HelpInfo.cs
- ResourceDefaultValueAttribute.cs
- XsltArgumentList.cs
- ComboBox.cs
- EncryptedXml.cs
- Formatter.cs
- StatusBarItemAutomationPeer.cs
- EpmAttributeNameBuilder.cs
- CodeDefaultValueExpression.cs
- WebResponse.cs
- DataGridViewCellPaintingEventArgs.cs
- WorkflowInstanceProxy.cs
- CollectionEditVerbManager.cs
- NullRuntimeConfig.cs
- Odbc32.cs
- QueryExpr.cs
- UnsafeNativeMethods.cs
- SQLInt16.cs
- InternalSafeNativeMethods.cs
- DbConnectionPoolIdentity.cs
- BackStopAuthenticationModule.cs
- DCSafeHandle.cs
- XmlEventCache.cs
- SettingsProperty.cs
- ToolStripTextBox.cs
- ItemAutomationPeer.cs
- HtmlElementErrorEventArgs.cs
- AutoGeneratedField.cs
- OrderedDictionary.cs
- SmiXetterAccessMap.cs
- XpsFont.cs
- DnsEndPoint.cs
- ControlCollection.cs
- DataObjectPastingEventArgs.cs
- PasswordRecoveryDesigner.cs
- CookieParameter.cs
- AnnotationStore.cs
- SafePEFileHandle.cs
- RC2CryptoServiceProvider.cs
- SystemWebCachingSectionGroup.cs
- ServerIdentity.cs
- SlotInfo.cs
- Normalization.cs
- RelativeSource.cs
- ClientSponsor.cs