Wednesday, March 28, 2012

System.io.File

When using the File object how do you now whether the path you are putting, is the path of a file on the server or the path of a file on the client machine.

I want to transfer a file from the client machine to the server, does anyone know if the File object is suited for this?I guess the real question there is where did you get the path from.

If the path came from the Posted File - then it is most likely the file path / name from the client not and is not valid for saving on the server
What do you mean when you say where the path came from, what if i hard code a file path to be e.g c:/intepub/newfolder/file.txt

If i put that path into a file object, would that look at c: on the server or client?
It's always a Path on your server or another machine in your network, over which you (or rather the ASPNET worker process or some other user you let the worker process impersonate) have rights to access.

The only time you handle a client path, is when someone has uploaded a file to your server.
Ok, but thats what i want to do using asp.net, i want to allow users to upload a file from their machine to the server. I have done this successfully using Java, but wanted to know if its possible using .net
It's extremely easy using .Net. One line of code will suffice in this very simple scenario:


<%@. Page Language="VB" %>
<%@. import Namespace="System.IO" %>
<script runat="server">
Sub Button_Click( obj As Object, evnt As EventArgs )
inpFileName.PostedFile.SaveAs( Server.MapPath("") & Path.GetFileName(inpFileName.PostedFile.FileName) )
End Sub
</script>
<html>
<head>
<title>Upload file</title>
</head>
<body>
<form enctype="multipart/form-data" runat="Server">
<input id="inpFileName" type="file" runat="Server" /><br>
<asp:Button id="btnFileUp" onclick="Button_Click" Runat="Server" Text="Upload file" /></form>
</body>
</html>

This will save an uploaded file to the root of your web application. Remember to grant rights to write to the physical folder for the ASPNET account. By default the max file size to be uploaded using .Net is set to 4 mb (4096 kb). If you need to up this size, you set it in your application's Web.config file using:

<httpRuntime maxRequestLength="<size in kb you wish to allow>" />

Thanks very much

0 comments:

Post a Comment