Hi thanhthuy,
Refer the below sample. While searching it ignores the file extension.
HTML
<div>
<asp:TextBox ID="txtName" runat="server" /><asp:Button ID="btnSearch" Text="Search"
runat="server" OnClick="Search" />
<asp:GridView runat="server" ID="gvFiles" AutoGenerateColumns="false" EmptyDataText="No record found">
<Columns>
<asp:BoundField DataField="Text" HeaderText="File Name" />
<asp:BoundField DataField="Value" HeaderText="File Path" />
</Columns>
</asp:GridView>
</div>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
BindGrid(txtName.Text.ToLower());
}
private void BindGrid(string searchedFile = "")
{
string[] filePaths = System.IO.Directory.GetFiles(@"D:\Data", "*");
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
if (!string.IsNullOrEmpty(searchedFile))
{
if (System.IO.Path.GetFileName(filePath).Substring(0, System.IO.Path.GetFileName(filePath).LastIndexOf('.')).ToLower() == searchedFile.ToLower())
{
files.Add(new ListItem(System.IO.Path.GetFileName(filePath), filePath));
}
}
else
{
files.Add(new ListItem(System.IO.Path.GetFileName(filePath), filePath));
}
}
gvFiles.DataSource = files;
gvFiles.DataBind();
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
BindGrid(txtName.Text.ToLower())
End Sub
Private Sub BindGrid(Optional searchedFile As String = "")
Dim filePaths As String() = System.IO.Directory.GetFiles("D:\Data", "*")
Dim files As New List(Of ListItem)()
For Each filePath As String In filePaths
If Not String.IsNullOrEmpty(searchedFile) Then
If System.IO.Path.GetFileName(filePath).Substring(0, System.IO.Path.GetFileName(filePath).LastIndexOf("."c)).ToLower() = searchedFile.ToLower() Then
files.Add(New ListItem(System.IO.Path.GetFileName(filePath), filePath))
End If
Else
files.Add(New ListItem(System.IO.Path.GetFileName(filePath), filePath))
End If
Next
gvFiles.DataSource = files
gvFiles.DataBind()
End Sub