OpenFileDialog extensions similar to MS Paint's SaveFileDialog - c#

I am working on a WPF application where users will be able to upload photos. I wrote the following code for the file extensions.
OpenFIleDialog.Filter = "JPEG Images|*.jpg|PNG Images|*.png|GIF Images|*.gif|BITMAPS|*.bmp|TIFF Images|*.tiff|TIFF Images|*.tif";
When saving a file in ms paint we have options as following
here we can see that the same format (.bmp & .dib) is being used for 4 options.
My question is can this be done using OpenFileDialog. If so, how?

Its quite simple, just add your filter like this
openFileDialog.Filter = "Office Files(Document or Excel)|*.doc;*.docx;*.xlsx;*.xls|Word Document(*.doc *.docx)|*.doc;*.docx";
var result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
var selectedFile = openFileDialog.FileName;
var filterIndex = openFileDialog.FilterIndex;
if(filterIndex == 1)
{
/* Code to perform if first filter (Office files in this case) is selected */
}
else if (filterIndex == 2)
{
/* Code to perform if second filter (Word Document in this case) is selected */
}
Here you can see that *.doc & *.docx are repeated. So based upon the selected value you can decide which encoding (in your case) to apply.

Related

A Better way to rename XAML file class when renaming the file?

EDIT: The main issue when renaming the file is to rename xaml contents
My intuition is screaming that there is a better way to do this, but the following works, my question is to see if there a better or an already existing method that can do this
I have a small WPF app that loads xaml files and can be imported/edited and exported.
When the WPF app initialises it makes a placeholder xaml file that you can edit,
"StartingXamlFile.xaml" when exporting I used a SaveFileDialog and the user can change the name. But the contents of the XAML file is not changed according to the file name. Also when importing an existing XAMLfile then editing and exporting(changing name when exporting) the same thing occurs.
Solution:
I set up a Singleton object to hold the file name XamlFile with property content and path. Now the default is set to "StartingXamlFile" when importing this is replaced. This is done following Gang of four Singleton technique
SaveFile code that doesnt work:
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "StartingXamlFile"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*"; // Filter files by extension
// Show save file dialog box
var result = dlg.ShowDialog();
if (result == true)
{
File.WriteAllText(dlg.FileName, editedContent);
}
Save File code that does work using Replace:
if (result == true)
{
var name = Path.GetFileNameWithoutExtension(dlg.FileName);
var testing = XamlFile.Content.Replace(XamlFile.Path,name);
File.WriteAllText(dlg.FileName, testing);
}
Just to give this question an accepted answer, I have not found a better way to this other than:
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "StartingXamlFile"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*";
// Show save file dialog box
var result = dlg.ShowDialog();
if (result == true)
{
//X:Class replacement is done here
var name = Path.GetFileNameWithoutExtension(dlg.FileName);
var testing = XamlFile.Content.Replace(XamlFile.Path,name);
File.WriteAllText(dlg.FileName, testing);
}
XamlFile is a singleton object that contains the content of the xaml
and initial name of file when starting up or importing, so when you export it
replaces all references to the initial name

Bypassing save dialog box in WPF application

I am trying to bypass the save dialog box when using the SaveFileDialog class. I want to be able to write to a document without having to prompt a user to decide if they want to save or not, the file should automatically save when they click a button.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.RestoreDirectory = true ;
saveFileDialog1.InitialDirectory = #"C:\";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// Code to write the stream goes here.
}
I have tried removing the if statement as well as using...
saveFileDialog1.CreatePRompt = false;
Nothing seems to work... Any ideas?
I think you want to bypass the overwrite prompt dialog.
In this case you can use
saveFileDialog1.OverwritePrompt = false;
Otherwise, you don't need a SaveFileDialog and you can save your stream without using it.
I found my answer. The question I asked was actually two it seems. The first was how to bypass SaveFileDialog, I wanted to use saveFileDialog because it can remember the last folder it accessed and opens to that folder when performing a read/save. That being said I implemented this...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
This will set Directory to the location of my executable.
Next I got rid of SaveFileDialog and just wrote to a file without ever prompting the user.
Thanks for all the pointers and ideas!
The end result ended up...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
using(System.IO.StreamWriter file = new System.IO.StreamWriter(Directory, false))
{
// File contents
}
Works perfectly for what I need it for.
If you want to save but you need the user to pick a filename, I would use this:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//setup properties of Dialog
bool filenamepicked = false;
while (!filenamepicked)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//Save file
filenamepicked = true;
}
else
{
MessageBox.Show("You have to use a file name.");
}
}

DialogResult Filter multiple extensions

I want to display an open file dialog and filter both .csv and .txt files. I've set the filter accordingly but it's only showing .csv files.
Here's my code:
var dialog = new Microsoft.Win32.OpenFileDialog();
dialog.Filter = "CSV files (*.csv)|*.csv|txt files (*.txt)|*.txt";
bool? isOK = dialog.ShowDialog();
if (isOK == true)
{
ImportFilePath = dialog.FileName;
}
If you want to show multiple file types at the same time, you should include them in a single filter:
dialog.Filter = "Plain text files (*.csv;*.txt)|*.csv;*.txt";
Otherwise the user will have to select the type of file in the bottom Combobox of the dialog.
Msdn has some useful examples of this.

Creating and saving files in C#

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}

How to know which file is selected in open dialog in c#

I have to open a file dialog. In that I have to choose one file either an XML or MAP file. If the choosen file is MAP file then I have to do step-A or if the choosen file is XML then I have to do step-B. My question is how to know which file is selected from the dialog box application?
OpenFileDialog fileDialog1 = new OpenFileDialog();
fileDialog1.Filter = "XML Files|*.xml|MAP Files|*.map";
fileDialog1.ShowDialog();
How to know which file is selected from the above filter ?
You can use:
string fileName = OpenFileDialog.Filename;
if(fileName.EndsWith(".xml"))
{
//
}
else if(fileName.EndsWith(".map"))
{
//
}
I think you can't do that while it is open.
When user presses OK then pass OpenFileDialog.Filename in Path.GetExtension method or OpenFileDialog.Filename.Endswith(".xml").
Check if extension is XML then do x step otherwise y step.
EDIT
See for functionality that you require, there has to be an event in open file dialog.
There are 2 OpenFileDialog Class
System.Windows.Forms
Microsoft.Win32
Both have only one event OpenFileDialog.FileOK which you can look for.
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filename = openFileDialog1.FileName;
if (File.Exists(filename))
{
//do something here
}
}
The FileName attribute of OpenFileDialog is the file name selected.
You could even use similar extensions in a switch with stacked labels and use the default case for unsupported file types:
switch (extension)
{
case "xml":
case "xaml":
Debug.WriteLine("It's an XML!");
break;
case "map":
Debug.WriteLine("It's a map!");
break;
default:
MessageBox.Show("Please select an XML or MAP file");
// Show the dialog again
break;
}
Well, the above answers will work if luckily all the filters have different extensions. but if we are talking about different File versions with the same extension then we can get the selected filter through this code:
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Excel 97|*.xls|Excel 95|*.xls";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Filer index is 1 based.
switch (dlg.FilterIndex)
{
case 1:
//Filter name: Excel 97
break;
case 2:
//Filter name: Excel 95
break;
}
}

Categories

Resources