我在 WPF/C # 中有一个要求,点击一个按钮,收集一些数据,然后把它放在一个文本文件,用户可以下载到他们的机器。我可以看到前半部分,但是如何用“另存为”对话框提示用户呢?文件本身将是一个简单的文本文件。
使用 SaveFileDialog级。
SaveFileDialog
您只需要创建一个 保存文件对话框,并调用它的 ShowDialog 方法。
SaveFileDialog is in the Microsoft.Win32 namespace - might save you the 10 minutes it took me to figure this out.
到目前为止,两个答案都链接到 Silverlight SaveFileDialog类; WPF 变种有很大的不同和不同的名称空间。
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".text"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show save file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { // Save document string filename = dlg.FileName; }
Here is some sample code:
string fileText = "Your output text"; SaveFileDialog dialog = new SaveFileDialog() { Filter = "Text Files(*.txt)|*.txt|All(*.*)|*" }; if (dialog.ShowDialog() == true) { File.WriteAllText(dialog.FileName, fileText); }
到目前为止,所有的示例都使用 Win32名称空间,但是还有一个替代方案:
FileInfo file = new FileInfo("image.jpg"); var dialog = new System.Windows.Forms.SaveFileDialog(); dialog.FileName = file.Name; dialog.DefaultExt = file.Extension; dialog.Filter = string.Format("{0} images ({1})|*{1}|All files (*.*)|*.*", file.Extension.Substring(1).Capitalize(), file.Extension); dialog.InitialDirectory = file.DirectoryName; System.Windows.Forms.DialogResult result = dialog.ShowDialog(this.GetIWin32Window()); if (result == System.Windows.Forms.DialogResult.OK) { }
我使用扩展方法从视觉控制中获取 IWin32Window:
IWin32Window
#region Get Win32 Handle from control public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual) { var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource; System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle); return win; } private class OldWindow : System.Windows.Forms.IWin32Window { private readonly System.IntPtr _handle; public OldWindow(System.IntPtr handle) { _handle = handle; } System.IntPtr System.Windows.Forms.IWin32Window.Handle { get { return _handle; } } } #endregion
Capitalize()也是一种扩展方法,但不值一提,因为有很多例子可以将字符串的第一个字母大写。
Capitalize()