In .Net GUI Applications, Interaction with User on selecting files is a very basic topic. In the following code samples, I have demonstrate how to select files ( in comment code), more importantly, give an example code on how to get a folder name form the windows open dialog box. Something Interesting here is that you actually can’t get the folder name easily. (I mean select a folder, you can still select the file then get the full path, which include the folder name) The best option is to use FolderBrowserDialog !
Ok, now here is the sample code. Enjoy.
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
string startupPath = Application.StartupPath;
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
dialog.Description = "Open a folder which contains the xml output";
dialog.ShowNewFolderButton = false;
dialog.RootFolder = Environment.SpecialFolder.MyComputer;
if(dialog.ShowDialog() == DialogResult.OK)
{
string folder = dialog.SelectedPath;
foreach (string fileName in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
{
SQLGenerator.GenerateSQLTransactions(Path.GetFullPath(fileName));
}
}
}
//using (OpenFileDialog dialog = new OpenFileDialog())
//{
// dialog.Filter = "xml files (*.xml)|*.xml";
// dialog.Multiselect = false;
// dialog.InitialDirectory = ".";
// dialog.Title = "Select file (only in XML format)";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// SQLGenerator.GenerateSQLTransactions(Application.StartupPath + Settings.Default.xmlFile);
// }
//}
}
catch (Exception exc)
{
MessageBox.Show("Import failed because " + exc.Message + " , please try again later.");
}
}
3 comments:
Thanks a lot, it was very useful.
Great read thankyyou
Thanks greatt blog
Post a Comment