So I had a project which I needed to find out what files were being held in a given directory and write those back to the browser. This is very helpful in automating posting of files to a website by your users without you being involved in tedious static html updates. The key here is the System.IO .NET class. We are going to access the DirectoryInfo class so we can iterate through and pull back all file objects contained within. In the code below, the DirectoryInfo looks in the current directory as we’ve defined through Server.MapPath(“.”). We could just have easily directed this through stepping up the directory (i.e. c:\intepub\wwwroot\directoryread\filestoread\). Next, we tell it to grab all the files that end with an .aspx extension which screens out any text or pdf files we may not be interested in. In the FileInfo class, we extract the name of each file to wire up the hyperlink and print this back to the user. I’ve taken it one step further to strip out the hyphens and the .aspx file extension that we print back to the user so the file name “Reading-files-from-a-directory-using-csharp.aspx” becomes “Reading files from a directory using cSharp”. Much cleaner and user friendly. That FileInfo class has lots of cool properties including LastWriteTime, CreationTime, Length (for a full rundown on the FileInfo properties checkout Microsoft’s .NET Framework Developer Center).
↧