ASP.Net a list of files in a directory + link to file
I am creating a web form which will display a list of exception files from a directory. The files display properly, however, the link doesn't work. I've done some quick searches for a solution, only issue is most solutions request I setup a virtual directory, however the server these files are located on is not a开发者_开发问答 web server. Here is the code which lists the files:
var exDir = @"\\Server\folder\Exception";
exLabel.Text = "";
foreach (string exFile in Directory.GetFiles(exDir))
{
exLabel.Text += @"<a href='file:"+exFile+"'> "+exFile+" </a><br/>";
}
The issue lies within my "href". Is there some way to setup this link without having to setup a virtual directory? Or if I have to setup one, do so via IIS Express?
You cannot do this without a virtual directory if the files do not reside on the same server as the web server. The files need to be served to clients via a web server.
While you can use IIS Express to create virtual directories - have a look at this discussion thread. You may also need to enable external access to IIS Express (this post on WebMatrix should be helpful in this regard). Note: when using a virtual directory, your URLs will need to use the http: or https: scheme instead of file:.
Another approach would be to upload the files you want to share to a location on the web server and serve them from web server.
If referencing the local file system, you need to format hyperlinks as follows:
file:///c:/myfile.txt
I think you can achieve this using a downloader server side, that can access the files for you then serve them through http.
An httphandler, which ProcessRequest method could be (very semplified) like this:
public void ProcessRequest(HttpContext context)
{
if (context.Request.Params["file"] != null)
{
string filename = context.Request.Params["file"].ToString();
context.Response.Clear();
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.Buffer = true;
FileInfo fileInfo = new FileInfo(filename);
if (fileInfo.Exists)
{
context.Response.ContentType = /* your mime type */;
context.Response.AppendHeader("content-disposition", string.Format("attachment;filename={0}", fileInfo.Name));
context.Response.WriteFile(filename);
}
context.Response.End();
}
}
then you'll build the link to point you handler with the file as param:
var exDir = @"\\Server\folder\Exception";
DirectoryInfo dir = new DirectoryInfo(exDir);
foreach (FileInfo exFile in dir.GetFiles())
{
exLabel.Text += @"<a href='downloader.ashx?file="+ exFile.Name + "'> "+exFile.FullName+" </a><br/>";
}
Remember to setup the handler in the web.config:
<system.web>
<httpHandlers>
...
<add verb="*" path="downloader.ashx" type="YourNamespace.downloader"/>
</httpHandlers>
</system.web>
(Of course this sample is very simple and I think full of errors, but is just to clarify the way)
精彩评论