I am working on excel sheets in C# and i am struck to select only excel sheets. I tried the following code
OpenFileDialog browseFile = new OpenFileDialog();
browseFile.DereferenceLinks = true;
browseFile.Filter = "Excel|*.xls|Excel 2010|*.xlsx";
// browseFile.Filter = "Link Files (*.lnk)|*.lnk";
browseFile.Title = "Browse Excel file";
if (browseFile.ShowDialog() == DialogResult.Cancel)
Using this code am not only getting excel sheets but also ended up getting the shortcut files. Can anyone suggest how can i restrict the shortcut files too.
In addition to manual data filtering, Excel enables fully automated filtering based on data from the specified range of cells.
Please see if you are ok with the below approach.
In the meantime let me try if something is possible using reflections.
OpenFileDialog openKeywordsFileDialog = new OpenFileDialog();
openKeywordsFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openKeywordsFileDialog.Multiselect = false;
openKeywordsFileDialog.ValidateNames = true;
openKeywordsFileDialog.DereferenceLinks = false; // Will return .lnk in shortcuts.
openKeywordsFileDialog.Filter = "Excel |*.xlsx";
openKeywordsFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(OpenKeywordsFileDialog_FileOk);
var dialogResult = openKeywordsFileDialog.ShowDialog();
void OpenKeywordsFileDialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
OpenFileDialog fileDialog = sender as OpenFileDialog;
string selectedFile = fileDialog.FileName;
if (string.IsNullOrEmpty(selectedFile) || selectedFile.Contains(".lnk"))
{
MessageBox.Show("Please select a valid Excel File");
e.Cancel = true;
}
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With