To get the files in the directory, use a modified version of Solution1.
Create a class that inherits from System.IO.FileSystemInfo and override the required methods. (Unfortunately FileInfo is sealed so you cannot inherit from that class.)
By overriding ToString, you can show what ever value in the list box.
public class MyFileInfo : System.IO.FileSystemInfo
{
public MyFileInfo(string fileName)
: base()
{
this.FullPath = fileName;
}
public override string ToString()
{
return System.IO.Path.GetFileNameWithoutExtension(this.Name);
}
public override bool Exists
{
get { return System.IO.File.Exists(this.FullName); }
}
public override void Delete()
{
System.IO.File.Delete(this.FullName);
}
public override string Name
{
get { return System.IO.Path.GetFileName(this.FullName); }
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string Path = Server.MapPath("/images/");
foreach (string fileName in Directory.GetFiles(Path))
{
ListBox1.Items.Add(new MyFileInfo(fileName));
}
}
}
[UPDATE] For-loop variant upon request
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string Path = Server.MapPath("/images/");
string[] fileNames = Directory.GetFiles(Path);
for (int i=0; i < fileNames.Length; i++)
{
ListBox1.Items.Add(new MyFileInfo(fileNames[i]));
}
}
}
For showing the image when an item is selected in the ListBox, you can use the event
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MyFileInfo mfi = (listBox1.SelectedItem as MyFileInfo);
if (mfi != null)
{
Image img = Image.FromFile(mfi.FullName);
}
}
This solution might be a bit of an overkill, but it has the benefit of keeping track of your files full path and you can show what ever value in your list box row.