How do I show a Save As dialog in WPF? - c#

I have a requirement in WPF/C# to click on a button, gather some data and then put it in a text file that the user can download to their machine. I can get the first half of this, but how do you prompt a user with a "Save As" dialog box? The file itself will be a simple text file.

Both answers thus far link to the Silverlight SaveFileDialogclass; the WPF variant is quite a bit different and differing namespace.
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;
}

SaveFileDialog is in the Microsoft.Win32 namespace - might save you the 10 minutes it took me to figure this out.

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);
}

Use the SaveFileDialog class.

You just need to create a SaveFileDialog, and call its ShowDialog method.

All the examples so far use the Win32 namespace, but there is an alternative:
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)
{
}
I'm using an extension method to get the IWin32Window from the visual control:
#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() is also an extension method, but not worth mentioning as there are plenty of examples of capitalizing the first letter of a string out there.

Related

C# custom file extension filter

I'm trying to read a list of documents in a directory. I understand how the filter modifiers work at a high level and have used them before. However, this time I need to filter something that doesn't have a standardized extension (i.e. "*.txt" or *.pdf").
I'm using the example as found on....
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.filedialog.filter?view=net-5.0
using System;
using System.Windows.Forms;
namespace COMS2412_Readin
{
public partial class Form1 : Form
{
string Serial_num = null;
string INI_file_dir_temp = null;
string CONFIG_data = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Allow user to enter serial number and load it for useage later.
Serial_num = Serial_number_text.Text;
try
{
using (OpenFileDialog COMS_file_dialog = new OpenFileDialog())
{
COMS_file_dialog.InitialDirectory = "c:\\";
//Have dialog box filter out all files without the .INI extention.
COMS_file_dialog.Filter = "txt files (*.INI)|*.INI|All files (*.*)|*.*"; //Failed
// COMS_file_dialog.Filter = "*.INI"; //Failed
// COMS_file_dialog.Filter = "(*.INI)"; //Failed
// COMS_file_dialog.Filter = "(INI files | *.INI)"; //Failed
COMS_file_dialog.FilterIndex = 2;
COMS_file_dialog.RestoreDirectory = true;
if (COMS_file_dialog.ShowDialog() == DialogResult.OK)
{
//Check to make sure it was the correct file type.
INI_file_dir_temp = COMS_file_dialog.FileName;
}
}
}
catch
{
//Sorry there was an error with opening the file. Please ensure the file is not currently open.
}
}
}
}
The project I'm working on imports config files from an external piece of equipment. The problem is there are literally thousands of files, each with unusual file extensions. For example *.INI is one of the extensions I want to filter. I've tried just entering `*.INI as the argument but it didn't work. What am I missing? Is there a way to alter...
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
to filter specific file extensions?
Finally, have something that works...
openFileDialog.Filter = "(*.INI)|*.INI";
This filters out everything that isn't of the .INI extension. For me specifically, I had to run VS as admin and ensure the files were not hidden.

Multiple file upload without full path

I'm trying to upload multiple files and just get the filename of them.
When I'm trying to do that it just uploads one file.
So it uploads the files with the full path(And it works).
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames);// <-- this works, but here I get the full path
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
And so I get just the Filename but it uploads just one File:
private void bChooseFolder_Click(object sender, EventArgs e)
{
CoreClass.OPENDIALOG.Multiselect = true;
string oldFilter = CoreClass.OPENDIALOG.Filter;
CoreClass.OPENDIALOG.Filter = "(*.csv) | *.csv";
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, System.IO.Path.GetFileNameWithoutExtension(CoreClass.OPENDIALOG.FileName)); // <-- Doesn't work. Just one File.
CoreClass.OPENDIALOG.Filter = oldFilter;
CoreClass.OPENDIALOG.Multiselect = false;
}
OK, If you are developing WinForms app then you are using OpenFileDialog which contains 2 properties:
FileName gets or sets a string containing the file name selected in the file dialog box.
FileNames gets the file names of all selected files in the dialog box.
Then first one will never contains few files and you should use it only in Multiselect = false; mode.
If you need to show all file names in one textbox then you can use String.Join method and LINQ to enumerate collection and get file name without extension for each element:
if (CoreClass.OPENDIALOG.ShowDialog() == DialogResult.OK)
tbFolderPath.Text = string.Join(FileSeperator, CoreClass.OPENDIALOG.FileNames.Select(x => System.IO.Path.GetFileNameWithoutExtension(x)).ToArray()); // <-- Doesn't work. Just one File.

How to filter *.abc from *.abcd files when using OpenFileDialog?

I have created an OpenFileDialog object, called openFileDialog.
When calling openFileDialog.ShowDialog I want to be able to select files having only the extension ".abc" and not ".abcd".
Using the property:
this.openFileDialog.Filter = "*.abc";
does not work. ".abcd" files can also be selected.
Here is the full code:
var openFileDialog = GetOpenFileDialog("abc",
"*.abc",
"anything (*.abc)|*.abc",
"Select abc file to import...");
if (openFileDialog.ShowDialog() == DialogResult.OK)
{ DoJob(); }
Where GetOpenFileDialog is:
private OpenFileDialog GetOpenFileDialog(string defaultExt, string fileName, string filter, string title)
{
return new OpenFileDialog
{
DefaultExt = defaultExt,
FileName = fileName,
Filter = filter,
Title = title,
};
}
I would appreciate any help. Thanks!
Use the filter option of the OpenFileDialog
this.openFileDialog.Filter = "abc files (*.abc)|*.abc"
There is simply a filter property for FileDialogs - http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filter.aspx

WriteAllBytes Error

I am using the below code in C# in a WPF Application
I am using this method to save one file to disk:
private void executeSaveAttachment(object parameter)
{
SaveFileDialog dlg = new SaveFileDialog();
{
dlg.AddExtension = true;
dlg.DefaultExt = "xlsx";
dlg.Filter = "New Excel(*.xlsx)|*.*";
foreach (var table in Table)
{
if (dlg.ShowDialog() ?? false)
{
File.WriteAllBytes(dlg.FileName, table.Data);
}
}
}
}
I am trying to use this method to store multiple files to a location the user is able to choose but give it default filename from the Title Property and add .xlsx extension. The class is named Table and the Data Property is the binary.
Here is the method that is giving
Error 4 No overload for method 'WriteAllBytes' takes 1 arguments
private void executeSaveAttachments(object parameter)
{
{
System.Windows.Forms.FolderBrowserDialog flg = new System.Windows.Forms.FolderBrowserDialog();
foreach (var table in Table)
{
if (flg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllBytes(Path.Combine(flg.SelectedPath, table.Title + ".dat"));
}
}
}
}
As the error suggests, WriteAllBytes doesn't have an overload with one argument. You must specify the bytes to write, as well as the path. You have it right in your first block so simply do the same again:
File.WriteAllBytes(Path.Combine(flg.SelectedPath, table.Title + ".dat"), table.Data);
You are missing an argument and you aren't passing data to write to your location. Path.Combine(flg.SelectedPath, table.Title + ".dat") is one argument, you forgot to pass the second argument.
File.WriteAllBytes(
Path.Combine(flg.SelectedPath, table.Title + ".dat"),
table.Data
);

Load filenames without extension to CheckedListBox

I have a checkedListBox; wich loads files inside a folder; to run/open when checked.
What I'm trying to achieve is to:
- Load filenames without extension into the CheckedListBox.
I can retrieve:
"C:\Folder1\anotherfolder\myfile1.txt"
but; i just want to be retrieve: the "filename" (with or without the extention).
Something Like:
"myfile1.txt"
I was attempting to do this with folderBrowserDialog, but I have no idea on how to accomplish this.
My Current Code:
//...
private string openFileName, folderName;
private bool fileOpened = false;
//...
OpenFileDialog ofd = new OpenFileDialog();
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (!fileOpened)
{
ofd.InitialDirectory = fbd.SelectedPath;
ofd.FileName = null;
fbd.Description = "Please select your *.txt folder";
fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string foldername = fbd.SelectedPath;
foreach (string f in Directory.GetFiles(foldername))
checkedListBox1.Items.Add(f);
}
Can anyone point me in the right direction?
Thanks in advance.
You don't need an OpenFileDialog at all, simply change the line that adds the files to
checkedListBox1.Items.Add(Path.GetFileName(f));
Just remember to add
using System.IO;
And you can also reduce everything to one line code
checkedListBox1.Items.AddRange(Directory.GetFiles(fbd.SelectedPath).Select(x => Path.GetFileName(x)).ToArray());

Categories