How can I use Server.MapPath to upload a file onto a server which is mapped on my computer - c#

So far I know how to upload a file to a folder within my solution using the code below.
string root = HttpContext.Current.Server.MapPath("~/upload");
How can I save the file to a different location that is not within a solution i.e to a server location that is mapped to my pc.
string root = HttpContext.Current.Server.MapPath("/Z:/UploadFolder"); I have tried this but its not saving to the server so where I am going wrong?

You should use MapPath when you have a relative path and want to use the path to your project. for another path you don't need MapPath. just use it like this:
string root ="Z:\\UploadFolder";

You can map a virtual directory in IIS to the location you want to save to. For example, map a virtual directory of UploadFolder to z:\uploadfolder. Then, this will work:
string root = HttpContext.Current.Server.MapPath("~/upload");
Make sure you set permissions appropriately.

Your logic seems to be confusing. Use Server.MapPath - Returns the physical file path that corresponds to the specified virtual path.
But you are passing Physical Location to Server.MapPath in the second statement, which fails the whole purpose of Server.MapPath.
string root = HttpContext.Current.Server.MapPath("/Z:/UploadFolder"); **INCORRECT**
Ideally, you would need to create a virtual directory mapping to "/Z:/UploadFolder" and name it as "upload".
string root = HttpContext.Current.Server.MapPath("~/upload");
NB: You would need to pass explicit credentials to access the network share from ASP.NET. The suggested approach is to use Identity impersonation, once it is done retry with the same logic.
<configuration>
<system.web>
<identity impersonate="true" />
</system.web>
</configuration>

Related

How to delete file from relative path in asp.net

My Debugging screenshot
I am trying to delete a file in asp.net web 4.7.1. I'm using FileInfo and checking if file exists using a relative path the points to the Uploads folder and image full name and extension. I have saving the image path in my database and I know if I use full path I will delete the file. How can I delete using the saved path?
I am thinking of modifying my database for each Image to store full path and relative path. I will use the full path for deleting file only. How can I delete without having to create a second database field for storing a full path?
One of the best ways to solve such problem (So that application wouldn't face any challenge of path access or read\write access on windows drive level).
Create virtual director and use that virtual directory to save relative path. Set up all access on virtual directory which is one time task.
Then you can use that virtual directory relative path in your code instead of full path.

HttpContext Current Server MapPath : not getting the correct path

Beginner: Need some help in figuring out how can we do it. I am using MVC4 controller with c# and this is happeing in one of my actions
I am trying to get the path of a config file which is located at
c:\TestProj\www\config\config.xml
I am using this to get the path
var expectedPath = HttpContext.Current.Server.MapPath("~\config\config.xml")
but when i run my action what i am getting in my expected path is
c:\Test\www\config\config.xml
I am not sure why..can some one please make some suggestions
~ represents the application path.
May be your application is located on c:\Test\www.
Either place config.xml on C:\test\www\config\config.xml
or move your application to the C:\testproj folder
or use a different method instead of MapPath, that uses absolute path.

Create folder from one site in another's folder

There is a folder for file uploads on my site http://mySite/Uploads/
for each user I want to create a new folder and save files into it. It works for site visitors/ But i also have an admin site. Employees should be able to upload files with it at the same directory.
Directory.CreateDirectory returns an error, that it can't handle uri addresses.
I'm passing "http://mySite/Uploads/UserId". am i wrong? should i use another mechanisms?
am i wrong?
Yes, you should pass a physical folder to the Directory.CreateDirectory method and not an url. For example:
Directory.CreateDirectory(Server.MapPath("~/uploads/UserId"));
The Server.MapPath method should return a folder like this: c:\inetpub\wwwroot\mysite\uploads\userid.
You must use paths relative to the system root. You can do that with the MapPath method.
var uploadsRoot = Server.MapPath("~Uploads");
var userUploadFolder = Path.Combine(UploadsRoot, userId.ToString());
Directory.CreateDirecty(userUploadFolder);
If anyone interested. We made virtual folder "uploads" in IIS in both sites. Right click on your site in iis => add virtual folder or somehow, my iis isn't in english. Do it for both sites. and it's full path points at the same folder, so i can use Server.MapPath("~Uploads"); and in admin site i get http://adminSite/Uploads/, in main site it's http://mySite/Uploads/. if i upload files by one address, i allways can get access to them by another.

how do I access a folder on the shared hosting space?

I am trying to upload image files to the server and it gives me an error
"System.UnauthorizedAccessException: Access to the path 'D:\Hosting\234344\html\Testingfiles\upload\813.jpg' is denied.at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)"
in the HttpHandler I have :
HttpPostedFile file = context.Request.Files["Filedata"];
string usr_id = context.Request.Form["usr_id"];// gets the JSON data from the request
string strPath = context.Server.MapPath(("/Testingfiles/upload/") + file.FileName);
string ext = Path.GetExtension(strPath);
if (ext.Equals(".jpg") || ext.Equals(".jpeg") || ext.Equals(".png"))
{
file.SaveAs(strPath);
context.Response.Write("Image uploaded successfully");
}
what am i doing wrong here?
The error message says it all. You don't have write access to that folder.
You will need to ask your hosting provider to assign write rights to that folder for the ASP .NET identity.
Also, consider if you can use a folder below ~/App_Data. This is by convention the place to store files that needs write access in ASP .NET, so many hosting providers will allow writes to this folder by default (but you would need to check yourself for your specific host to be sure).
You should try writing to ~/App_Data/ to see if that works. If it does then its just because you haven't given asp.net write permission to the /TestingFiles/Uploads/ folder.
If your control panel has Plesk on it then you can sort this out yourself by going to the FileManager and clicking the permissions button. If you look at your App_Data file permissions for reference, the actual username that you need to add will vary depending on your domain name with plesk.
Other hosting control panels may allow you to do it in different ways.
If you can't find it then you should ask your host how you set up file permissions or look in their knowledge base.
If your control panel has Plesk on it then you can sort this out yourself by going to the FileManager and clicking the permissions button.
I fixed this error by allowing IIS users full access to upload folder. No need to use App_Data folder
For Plesk 12.0 only:
No need to use App Data folder. You just have to give full control to your Application pool group IWPG(username). It will surely work. I searched for many hours and this solution worked for me .
Hope It works for others too.

How do I read a file located in a same folder where my page resides in in ASP.NET?

How do I read a file located in a same folder where my page resides in in ASP.NET (C#)?
I have a page called mypage.aspx and I'm trying to read in a file called foo.txt residing in a same directory as this page.
Is there a way to open that file for reading with File.OpenRead()?
Providing a relative path like File.OpenRead("foo.txt") fails b/c of the location of the file.
It should be something like
File.OpenRead(Server.MapPath("foo.txt"));
You should try File.OpenRead(Server.MapPath("foo.txt")).
If MapPath doesn't expand/can't find the proper path at this point then try it while specifying the relative path to the page in question starting from the sites virtual root (using the tilde (~) at the beginning of the string to indicate this), i.e. File.OpenRead(Server.MapPath("~/path/foo.txt"))
In ASP.NET the folder is really IIS's folder which is typically in C:\Windows\System32\Inetsrv\ etc.
What you will need to do is use either
Server.MapPath("TheFileName").
Or get the PhysicalApplicationPath from the Request using
Request.PhysicalApplicationPath
or
HttpRuntime.AppDomainAppPath
and go from the Request and then go from there
You can use a label message or textbox in the aspx page and you can display the file in that by using the below code, I had used a label message wit lblDisplay ID.
lblDisplay.Text = File.ReadAllText(Server.MapPath("Give the path here"));

Categories

Resources