Validate File Extension Windows application
For this first we will create a new windows application and add textbox and a button control to browse the files and for submit button.
Now crate click event for Browse button and add the below code on click event of button.
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files (.xls,.xlsx)|*.xls;*.xlsx";
if (ofd.ShowDialog() == DialogResult.OK)
{
txtPath.Text = ofd.FileName;
}
}
In above code I have created object of OpenFileDialog and added Filter to allow user to select only the excel file. ShowDialog() to show option to select the file window. Now ones the user click on ok. Here by using DialogResult.OK validated user have done by selecting the file. Here ofd.Filter = "Excel Files (.xls,.xlsx)|*.xls;*.xlsx"; used to force to select only excel file. Now lets run and click on brose file. In above you can see we are having option to select only the excel file. Now click on ok. We will be able to get the file path in textbox.
private void btnSubmit_Click(object sender, EventArgs e)
{
string ext = Path.GetExtension(txtPath.Text);
if (ext == ".xls" || ext == ".xlsx")
{
MessageBox.Show("You selected correct file.");
}
else
{
MessageBox.Show("Error !!!wrong file selected.");
}
}
Here in above for submit button I have extracted the file extension Path.GetExtension() method by passing file path. Here is user have selected correct file like excel on that case he will get message for correct file selection otherwise he will get error message. Now let's change the file extension and click on submit. You will get error.Validate File Extension Console application
Here we will keep things simple. We will just pass the file path and get the file extension and display message. Let's pass not excel file and check the output.
string path = "C:\\DB\\EmployeeDB.db";
string ext = Path.GetExtension(path);
if (ext == ".xls" || ext == ".xlsx")
{
Console.WriteLine("You selected correct file.");
}
else
{
Console.WriteLine("Error !!!wrong file selected.");
}
Console.ReadLine();
In above code I have passed file path and Path.GetExtension(path); is used to get file extension. Now let's run the code to check the output.