Cómo mostrar sólo ciertas imágenes en una carpeta en un repetidor en ASP.NET
-
05-09-2019 - |
Pregunta
Tengo un repetidor que tiene todas mis imágenes en una carpeta y mostrarlo. Pero, ¿qué cambios de código debo hacer sólo para permitir digamos que Image1.jpg y Image2.jpg que se mostrarán en mi repetidor. I don "t desea el repetidor para mostrar todas las imágenes en mi carpeta.
Mi repetidor
<asp:Repeater ID="repImages" runat="server" OnItemDataBound="repImages_ItemDataBound">
<HeaderTemplate><p></HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="hlWhat" runat="server" rel="imagebox-bw">
<asp:Image ID="imgTheImage" runat="server" />
</asp:HyperLink>
</ItemTemplate>
<FooterTemplate></p></FooterTemplate>
</asp:Repeater>
Mi código detrás - carga de la página
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sBasePath = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
if ( sBasePath.EndsWith("\\"))
sBasePath = sBasePath.Substring(0,sBasePath.Length-1);
sBasePath = sBasePath + "\\" + "pics";
System.Collections.Generic.List<string> oList = new System.Collections.Generic.List<string>();
foreach (string s in System.IO.Directory.GetFiles(sBasePath, "*.*"))
{
//We could do some filtering for example only adding .jpg or something
oList.Add( System.IO.Path.GetFileName( s ));
}
repImages.DataSource = oList;
repImages.DataBind();
}
}
Mi código detrás - código de evento ItemDataBound del repetidor
protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem ||
e.Item.ItemType == ListItemType.Item)
{
string sFile = e.Item.DataItem as string;
//Create the thumblink
HyperLink hlWhat = e.Item.FindControl("hlWhat") as HyperLink;
hlWhat.NavigateUrl = ResolveUrl("~/pics/" + sFile );
hlWhat.ToolTip = System.IO.Path.GetFileNameWithoutExtension(sFile);
hlWhat.Attributes["rel"] = "imagebox-bw";
Image oImg = e.Item.FindControl("imgTheImage") as Image;
oImg.ImageUrl = ResolveUrl("~/createthumb.ashx?gu=/pics/" + sFile + "&xmax=100&ymax=100" );
}
}
RESPUESTA:
Mi Página actualizada de carga
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sBasePath = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
if ( sBasePath.EndsWith("\\"))
sBasePath = sBasePath.Substring(0,sBasePath.Length-1);
sBasePath = sBasePath + "\\" + "pics";
System.Collections.Generic.List<string> oList = new System.Collections.Generic.List<string>();
string[] extensions = { "*.jpg", "*.png" };
List<string> files = new List<string>();
foreach (string filter in extensions)
{
files.AddRange(System.IO.Directory.GetFiles(sBasePath, filter));
oList.Add(System.IO.Path.GetFileName(filter));
}
repImages.DataSource = oList;
repImages.DataBind();
}
Solución
¿En qué formato son los nombres de las imágenes que desea mostrar? Si sabe que se puede construir un filtro para usar cuando se enumeran los contenidos del directorio:
string[] files = Directory.GetFiles(folder, "*1.jpg");
aparecerá una lista de todos los archivos jpg que terminan en "1"
EDIT:
En lugar de tener:
foreach (string s in System.IO.Directory.GetFiles(sBasePath, "*.*"))
{
//We could do some filtering for example only adding .jpg or something
oList.Add( System.IO.Path.GetFileName( s ));
}
Tendrías:
string[] files = System.IO.Directory.GetFiles(sBasePath, "*.jpg")
foreach (string s in files)
{
oList.Add( System.IO.Path.GetFileName( s ));
}
EDIT 2:
He hecho una búsqueda rápida y parece que se obtienen archivos no tomará varias extensiones, por lo que tendrá que buscar para cada tipo de extensión por separado:
string[] extensions = {"*.jpg" , "*.png" };
List<string> files = new List<string>();
foreach(string filter in extensions)
{
files.AddRange(System.IO.Directory.GetFiles(path, filter));
}
foreach (string s in files)
{
oList.Add( System.IO.Path.GetFileName( s ));
}
Otros consejos
La manera más fácil es cargar a todos en una lista <> y luego usar LINQ para filtrar las que desee.
VS2005
public class GetFiles
{
public static void Main(string[] args)
{
FileInfo[] files =
new DirectoryInfo(@"D:\downloads\_Installs").GetFiles();
ArrayList exefiles = new ArrayList();
foreach (FileInfo f in files)
{
if (f.Extension == ".exe") // or whatever matching you want to do.
{
exefiles.Add(f);
}
}
foreach (FileInfo f in exefiles)
{
Console.WriteLine(f.FullName);
}
Console.ReadKey();
}
}
VS2008
public class GetFiles
{
public static void Main(string[] args)
{
FileInfo[] files =
new DirectoryInfo(@"D:\downloads\_Installs").GetFiles();
var exefiles = from FileInfo f in files
where f.Extension == ".exe"
select f;
foreach (FileInfo f in exefiles)
{
Console.WriteLine(f.FullName);
}
Console.ReadKey();
}
}
Lo que hay que hacer es filtrar todas las imágenes que no desea mostrar en su lista antes de enlazar a su control del repetidor.