In this article I will explain with an example, how to get full path from FileUpload control in ASP.Net using C# and VB.Net.
The Misunderstanding
The developers tend to access the path of the file on the User’s machine that he has selected for upload in browsers like Internet Explorer (IE), Firefox, Chrome, Safari and Opera. It is displayed as fakepath.
The Reason
Initially, the full path of the File on the User’s machine was sent to the server, but later due to security reasons browsers is returning only file name instead of full path from client machine, as the path was being used to hack the computer.
Hence, now the location of the folder of the file on the User’s machine is not sent to the server and there is no need for the location of the file i.e. its full path for saving.
Solution
HTML Markup
The HTML Markup consists of following controls.
FileUpload – For selected the file.
Button – For uploading selected file.
The Button has been assigned with an OnClick event handler.
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="OnUpload" />
Namespaces
You will need to import the following namespace.
C#
VB.Net
Getting Full Path from FileUpload control in C# and VB.Net
When the Upload Button is clicked, the filename is extracted from the FileName property of the PostedFile property using the GetFileName function of the Path class.
Finally, the uploaded file is saved into the Uploads Folder (Directory) using SaveAs method.
C#
protected void OnUpload(object sender, EventArgs e)
{
string fileName = Path.GetFileName(fuUpload.PostedFile.FileName);
fuUpload.PostedFile.SaveAs(Server.MapPath("~/Uploads/" + fileName));
}
VB.Net
Protected Sub OnUpload(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = Path.GetFileName(fuUpload.PostedFile.FileName)
fuUpload.PostedFile.SaveAs(Server.MapPath("~/Uploads/" & fileName))
End Sub
Screenshot
Downloads