Saturday, January 19, 2013

Example File Browser in ASP.NET


You can use methods such as DirectoryInfo.GetFiles() and DirectoryInfo.GetDirectories() to create a simple file browser. The following example shows you how. Be warned that, although this code is a good example of how to use the DirectoryInfo and FileInfo classes, it isn’t a good example of security. Generally, you wouldn’t want a user to be able to find out so much information about the files on your web server. The sample file browser program allows the user to see information about any file in any directory in the current drive, as shown in Figure.


The code for the file browser page is as follows:

public partial class FileBrowser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string startingDir = @"c:\";
lblCurrentDir.Text = startingDir;
ShowFilesIn(startingDir);
ShowDirectoriesIn(startingDir);
}
}

private void ShowFilesIn(string dir)
{
lstFiles.Items.Clear();
try
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
foreach (FileInfo fileItem in dirInfo.GetFiles())
{
lstFiles.Items.Add(fileItem.Name);
}
}
catch (Exception err)
{
// Ignore the error and leave the list box empty.
}
}

private void ShowDirectoriesIn(string dir)
{
lstDirs.Items.Clear();
try
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
foreach (DirectoryInfo dirItem in dirInfo.GetDirectories())
{
lstDirs.Items.Add(dirItem.Name);
}
}
catch (Exception err)
{
// Ignore the error and leave the list box empty.
}
}

protected void cmdBrowse_Click(Object sender, EventArgs e)
{
// Browse to the currently selected subdirectory.
if (lstDirs.SelectedIndex != -1)
{
string newDir = Path.Combine(lblCurrentDir.Text,
lstDirs.SelectedItem.Text);
lblCurrentDir.Text = newDir;
ShowFilesIn(newDir);
ShowDirectoriesIn(newDir);
}
}

protected void cmdParent_Click(object sender, EventArgs e)
{
// Browse up to the current directory's parent.
// The Directory.GetParent() method helps us out.
if (Directory.GetParent(lblCurrentDir.Text) == null)
{
// This is the root directory; there are no more levels.
}
else
{
string newDir = Directory.GetParent(lblCurrentDir.Text).FullName;
lblCurrentDir.Text = newDir;
ShowFilesIn(newDir);
ShowDirectoriesIn(newDir);
}
}

protected void cmdShowInfo_Click(object sender, EventArgs e)
{
// Show information for the currently selected file.
if (lstFiles.SelectedIndex != -1)
{
string fileName = Path.Combine(lblCurrentDir.Text,
lstFiles.SelectedItem.Text);
StringBuilder displayText = new StringBuilder();
try
{
FileInfo selectedFile = new FileInfo(fileName);
displayText.Append("<b>");
displayText.Append(selectedFile.Name);
displayText.Append("</b><br />Size: ");
displayText.Append(selectedFile.Length);
displayText.Append("<br />");
displayText.Append("Created: ");
displayText.Append(selectedFile.CreationTime.ToString());
displayText.Append("<br />Last Accessed: ");
displayText.Append(selectedFile.LastAccessTime.ToString());
}
catch (Exception err)
{
displayText.Append(err.Message);
}
lblFileInfo.Text = displayText.ToString();
}
}
}

Dissecting the Code . . .

• The list controls in this example don’t post back immediately. Instead, the web page relies on the Browse to Selected, Up One Level, and Show Info buttons.

• By default, directory names don’t end with a trailing backslash (\) character (for example, c:\Temp is used instead of c:\Temp\). However, when referring to the root drive, a slash is required. This is because of an interesting inconsistency that dates back to the days of DOS. When using directory names, c:\ refers to the root drive, but c: refers to the current directory, whatever it may be. This quirk can cause problems when you’re manipulating strings that contain file names, because you don’t want to add an extra trailing slash to a path (as in the invalid path c:\\myfile.txt). To solve this problem, the page uses the Combine() method of the Path class. This method correctly joins any file and path name together, adding the \ when required.

• The code includes all the necessary error-handling code. If you attempt to read the information for a file that you aren’t permitted to examine, the error message is displayed instead of the file details section. If an error occurs when calling DirectoryInfo.GetFiles() or DirectoryInfo.GetDirectories(), the error is simply ignored and the files or subdirectories aren’t shown. This error occurs if the account that’s running your code doesn’t have permission to read the contents of the directory. For example, this occurs if you try to access the c:\System Volume Information directory inWindows.

• The ShowFilesIn() and ShowDirectoriesIn() methods loop through the file and directory collections to build the lists. Another approach is to use data binding instead, as shown in the following code sample:

// Another way to fill lstFiles.
DirectoryInfo dirInfo = new DirectoryInfo(dir);
lstFiles.DataSource = dirInfo.GetFiles();
lstFiles.DataMember = "Name";
lstFiles.DataBind();

Just remember that when you bind a collection of objects, you need to specify which property will be used for the list. In this case, it’s the DirectoryInfo.Name or FileInfo.Name property.

No comments:
Write comments
Recommended Posts × +