我需要将文件夹中的文件名显示为GridView控件。
我认为使用目录类。
在我的数据库中,我有 sFolder 列,每行都有此值:
control/Imp/foo
我在网上尝试了这个tutorial,但我无法将文件夹中的文件名转换为GridView控件。
我没有错误,但即使文件夹的路径正确,GridView也是空的。
我的代码如下。
你能帮助我吗?
提前感谢您的任何帮助,非常感谢
的.cs
dt2 = new DataTable();
ds2 = new DataSet();
sql = @String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
的.aspx
<asp:GridView ID="gvDownload" EmptyDataText="Data empty"
runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" GridLines="Vertical">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
</Columns>
</asp:GridView>
#Edit 01
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
RetrieveProductsDowload();
}
private DataSet RetrieveProductsDowload()
{
dt2 = new DataTable();
ds2 = new DataSet();
sql = @String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
}
答案 0 :(得分:3)
请试试这个:
string[] allfiles = Directory.GetFiles(FilePath, "*", SearchOption.AllDirectories);
gvDownload.DataSource = allfiles;
gvDownload.DataBind();