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;
}
}
Related
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.");
}
}
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.
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");
}
I have a console application in which we are creating xlsx files using OPENXML, we are able to create xlsx file & save it into specific folder in application.
But Now we want to show that file as a Save/Open dialog pop up. Then we can able to specify a particular path to save/ to open the existing files.
I am new to this OpenXml, Can anyone please help me on this to proceed further? How can I acheive this? Do we have any built-in DLL for this?
Thanks.
se the Save file dialog. It will prompts the user to select a location for saving a file. After that you can use saveFileDialog.FileName.ToString() property to get the full path.
See the sample code below:
//Save a file in a particular format as specified in the saveAsType parameter
private void OpenSaveFileDialog(int saveAsType)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog.Filter = "CSV|*.csv|Excel|*.xlsx";
saveFileDialog.FilterIndex = saveAsType;
saveFileDialog.Title = "Save Data";
saveFileDialog.FileName = "My File";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName != "")
{
//File Path = m_fileName
m_fileName = saveFileDialog.FileName.ToString();
//FilterIndex property is one-based.
switch (saveFileDialog.FilterIndex)
{
case 1:
m_fileType = 1;
break;
case 2:
m_fileType = 2;
break;
}
}
}
Ref:http://msdn.microsoft.com/en-us//library/system.windows.forms.savefiledialog.aspx
Hi all i have written a code to display a message box if invalid characters are entered while saving the file but my message box is not displaying. Actually i will have a save file dialog option to save a file if the filename starts or consists of the following
\\/:*?<>|"
I would like to display a message box as invalid or illegalcharacters in file
My code is as follows
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "(*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileName = saveFileDialog1.FileName;
if ((FilePathHasInvalidChars(FileName)))
{
MessageBox.Show("File name should not contain \\/:*?<>|" ,"", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
//FileName = saveFileDialog1.FileName;
if (!(FilePathHasInvalidChars(FileName)))
{
TreeNode newNode = new TreeNode(FileName);
newNode.SelectedImageIndex = 1;
tvwACH.SelectedNode.Nodes.Add(newNode);
TreeNode NodeFileHeader = newNode.Nodes.Add("FileHeader");
myStream.Close();
}
}
}
}
public static bool FilePathHasInvalidChars(string path)
{
return (!string.IsNullOrEmpty(path) && path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0);
}
Can any one help me
The SaveFileDialog class has a property called ValidateNames. It the value of that property is true(which it is by default, no need to assign it), the dialog will automatically validate that the name the the user enters does not contain any illegal characters. If the user enters an illegal file name and clicks the "Save" button, the dialog will not close, but instead show an error message:
(yes, I am currently using Windows XP)
This is because the FileDialog does this check already on himself.
If you try to use a < or a > within a filename you get an error message. If you try to use a search pattern like ? or * the ListView will be filtered for the given pattern.
Set the property ValidateNames to true in the saveFileDialog1 instance as per this MSDN. And that is set to default to be true at run-time instantiation of the 'SaveFileDialog' class.
If you're talking about having a customized error message handler to display a custom message, you need to override the SaveFileDialog by sub-classing it and intercepting the windows procedure messages for this class. Have a look at this article on CodeProject which shows how to do it.