Set write permission on folder create - c#

Hi I have been trying to properly configure IIS 6 to give write permisiosn for about 2 days now and I can't seem to find any good resource on this.I am a bit new to ASP.NET and until now I never had to work with IIS.
What I am trying to do is upload a file to the server.Each user on the server will have his own special folder witch will be created automaticly via C#.Now when I try to upload the file I get this error:
Access to the path 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru' is denied
This is my code for creating the folder for each user and saving the file:
private void addImageToApp()
{
string path = "~/Images/avatar/userAvatars/" + User.Identity.Name;
createPath(path);
if( Directory.Exists(HostingEnvironment.MapPath(path)))
{
try {
UploadImage.SaveAs(HostingEnvironment.MapPath(path));
MultiViewIndex.ActiveViewIndex = 0;
}catch(Exception ex)
{
AvatarDetails.Text = ex.Message;
}
}
}
private void createPath(string path)
{
string activeDir = HostingEnvironment.MapPath("~/Images/avatar/userAvatars");
if( !Directory.Exists(Server.MapPath(path)) )
{
string newPath = Path.Combine(activeDir, User.Identity.Name);
Directory.CreateDirectory(newPath);
}
}
All I could find on the internet is that I have to add write permision via folder/properties/security/... while that is all good and fine I can not do this for each folder.
Up to this point I am not really sure that IIS is the one I need to configure I am a bit lost at this.
What do I have to do to give folders write permisions automaticly on folder create?
And if anyone has a good article or tutorial that shows how to do this please share it with me all the info I could find were very basic.
EDIT
I have added the network service account to the Images folder with full permision and have set the application's pool Identity to NetworkService but I still get the same error
EDIT
I have messed around with SQL-SERVER for the last couple of days in order to make this work so I might have missconfigured something form what I understand NETWORK SERVICE is stored in SQL-SERVER master.db database.I seem to be having two network service logins may this be the problem?I remember when I first checked it I had none now I have two:

Simply, when your asp.net application running you can open Task Manager and find process w3wp.
W3wp process like any other has user identity (by default - application pool identity - DefaultAppPool(like application pool name)).
And if it so, you should add write permissions for user named DefaultAppPool. To do it you should open security tab in folder's properties window, then change->add and type IIS AppPool/DefaultAppPool and choose local machine.
This post should help you!

This has nothing to do with IIS, brother. All you need to do is, open your IIS. Go to Application Pool. Right click on the Application Pool your website is running with. Select "Advanced Settings" and see the entry made against IDENTITY. Change it to use NetworkService. This will mean that you will be running your website under NETWORK SERVICE account now on.
Now right-click your root images folder, i.e., "Images". Select PROPERTIES. Select SECURITY. Add user NETWORK SERVICE, and give it FULL RIGHTS permissions on the folder.
Now whenever you create a folder and file under this "Images" folder through your code, it will automatically inherit permissions from its parent and you will allow you to do whatever you want (Add/Delete).
I hope this answers your question. If yes, then please mark it as "answered".

Related

Can't see path to another server in ASP.NET MVC

I have an internal ASP.NET MVC site that needs to read an Excel file. The file is on a different server from the one that ASP.NET MVC is running on and in order to prevent access problems I'm trying to copy it to the ASP.NET MVC server.
It works OK on my dev machine but when it is deployed to the server it can't see the path.
This is the chopped down code from the model (C#):
string fPath = HttpContext.Current.Server.MapPath(#"/virtualdir");
string fName = fPath + "test.xlsm";
if (System.IO.File.Exists(fName))
{
// Copy the file and do what's necessary
}
else
{
if (!Directory.Exists(fPath))
throw new Exception($"Directory not found: {fPath} ");
else
throw new Exception($"File not found: {fName } ");
}
The error I'm getting is
Directory not found:
followed by the path.
The path in the error is correct - I've copied and pasted it into explorer and it resolves OK.
I've tried using the full UNC path, a mapped network drive and a virtual directory (as in the code above). Where required these were given network admin rights (to test only!) but still nothing has worked.
The internal website is using pass through authentication but I've used specific credentials with full admin rights for the virtual directory, and the virtual dir in IIS expands OK to the required folder.
I've also tried giving the application pool (which runs in Integrated mode) full network admin rights.
I'm kind of hoping I've just overlooked something simple and this isn't a 'security feature'.
I found this question copy files between servers asp.net mvc but the answer was to use FTP and I don't want to go down that route if I can avoid it.
Any assistance will be much appreciated.
First, To be on the safe side that your directory is building correctly, I would use the Path.Combine.
string fName = Path.Combine(fPath, "test.xlsm")
Second, I would check the following post and try some things there as it seems to be a similar issue.
Directory.Exists not working for a network path
If you are still not able to see the directory, there is a good chance the user does not have access to that network path. Likely what happened is the app pool running your application has access to the directory on the server. The production box likely doesn't have that same access. You would have to get with the network engineer to get that resolved.
Alternatively, you could write a Powershell script to run as a user who has access to both the production and the development server to copy the file over to the production server if that is your ultimate goal and your server administrators could schedule it for you if that is allowed in your environment.

Creating a folder on the desktop

I want to create a folder on my current user's desktop folder, however; I keep getting an access denied message. I have full write permissions under my profile in IIS.
string activeDir = #"C:\Users\dmm\Desktop\";
string newPath = System.IO.Path.Combine(activeDir, "mySubDir");
System.IO.Directory.CreateDirectory(newPath);
Any help would be appreciated.
Try using the built in objects to get the desktop path, and let .NET also handle the path building for the new folder. You will also want to check if the directory exists first.
string newFolder = "abcd1234";
string path = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
newFolder
);
if(!System.IO.Directory.Exists(path)) {
try {
System.IO.Directory.CreateDirectory(path);
} catch (IOException ie) {
Console.WriteLine("IO Error: " + ie.Message);
} catch (Exception e) {
Console.WriteLine("General Error: " + e.Message);
}
}
When you deploy an application on IIS by default it is executed with ApplicationPoolIdentity. Which is virtual user created and named as IIS AppPool\YourPoolName If this virtual user does not have write access to your desktop. You get that exception.
You have two options.
Give ApplicationPoolIdentity user write access to Desktop directory.
goto Desktop folder and add user IIS AppPool\YourPoolName with write access :
Change pool Identity to user which has write access to directory.
Go
IIS->Application Pools -> Your AppPool ->Advanced Settings -> Identity
->
Select Custom Account and click set button. and there you enter your windows user credentials.
I would recommend first option.
There are many to consider here, first of them being that your application is an ASP.NET application, and every current user will be different. If your application — just assume — runs correctly on your machine, it will never run on hosting environment because they do not grant write permissions to special folders and user accounts.
That said, you need to work in physical paths in order to create your directories.
var path = "C:\\Users\\afzaa\\Desktop\\";
var folder = Path.Combine(path, "folder");
Directory.CreateDirectory(folder);
The result of the above code is,
As you can see, the code properly works and has no issue at all in execution.
There are few things to note:
Your application has read/write permissions. Check IIS for that.
Your code can actually lookup the path you are trying to access. That applies to any folder inside Desktop too, a sub folder may have special permissions applied.
Do not do this, write the content online in your hosting domain. Users have different accounts and structures for folders and thus this will not work — Desktop path is different.
If you want to users to download the file, simply stream the file down and let them save it where they want to.
https://forums.asp.net/t/1807775.aspx?Create+e+New+Folder+Access+Denied+
https://answers.microsoft.com/en-us/windows/forum/windows_xp-files/unable-to-create-the-folder-new-folder-access-is/ac318218-a7b2-4ee2-b301-2ad91856050b
.NET MVC Access denied when trying to create Directory
If you ran your logic from an IIS application, you should use Server.MapPath:
System.IO.Directory.CreateDirectory(Server.MapPath(newPath));

Upload images acces to path denied

Hi I seem to be having a problem when uploading images in asp.net.When I tryed to upload an Image I get this error:
Access to the path 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru' is denied.
I have set application pools Identoty to NETWORKSERVICE ando also added the NETWORK SERVICE account to the Images folder with full permision but I still get the same error.
This is my code:
private void addImageToApp()
{
string path = "~/Images/avatar/userAvatars/" + User.Identity.Name;
createPath(path);
if( Directory.Exists(HostingEnvironment.MapPath(path)))
{
//try {
UploadImage.SaveAs(HostingEnvironment.MapPath(path));
// MultiViewIndex.ActiveViewIndex = 0;
//}catch(Exception ex)
//{
// AvatarDetails.Text = ex.Message;
//}
}
}
private void createPath(string path)
{
string activeDir = HostingEnvironment.MapPath("~/Images/avatar/userAvatars");
if( !Directory.Exists(Server.MapPath(path)) )
{
string newPath = Path.Combine(activeDir, User.Identity.Name);
Directory.CreateDirectory(newPath);
}
}
What else can I do to solve this problem?
EDIT
Hi at this point I have full permision control to the following USERS:
Authetificated Users
IUSR
SYSTEM
NETWORK SERVICE
IIS_WPG
Administrator
USers
Is it posible that I need to set any configuration to IIS in order for this to work?
EDIT
I have messed around with SQL-SERVER for the last couple of days in order to make this work so I might have missconfigured something form what I understand NETWORK SERVICE is stored in SQL-SERVER master.db database.I seem to be having two network service logins may this be the problem?I remember when I first checked it I had none now I have two:
EDIT
This is the print with the permisions I added to the folder:
EDIT : Complete error
StackTrace:
In method CreatePath you are creating folder 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru'.
Then, you try to save the uploaded image with the filename 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru'.
You can't have a folder and a file with the same name. If you try to do this, the OS will tell you access is denied.
I suppose you want to either create a filename inside folder aleczandru, or you meant to save the file as aleczandru.png or something in folder userAvatars.
Assuming your UploadImage is a FileUpload control, you can save the file to the user's folder using the original file name of the uploaded file.
UploadImage.SaveAs(HostingEnvironment.MapPath(
Path.Combine(path, UploadImage.FileName)));
Pls make sure you have full filename with file extention in you path.
Ok... I have done this before for a project to implement a PUT method for http. I dont clearly remember it.. but some hints... if I were in my office I could tell you correctly. here are the hints
You need to add IIS_IUSRS to have access to the folder in windows.
Go to IIS admin console click the deployed site node, and set the permission for the same folder/website requests coming in... I dont remember the which category was it.. that settings pane will allow you to add/modify permissions for POST, GET and other verbs for that matter... when you edit that, you should see options for Administrator, a particular user account, anonymous etc.
may be I will write back tomorrow... exactly how to do it :-)
Try to give the group called users the permission to modify this directory (under security)
You need to find out what user the asp.net upload page is running under. If you haven't changed it, and are not running under impersonation, it should default to the ASPNET user on the local machine. Whatever it turns out to be, give that user read/write permissions on the folder.

Access denied error

I am trying to delete the excel file from a specipic location . but can't deleting. having error :
Access to the path 'C:\mypath\sample.xlsx' is denied.
I write a code as :
protected void imgbtnImport_Click(object sender, ImageClickEventArgs e)
{
try
{
string strApplicationPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath);
string strXLStoredDirectoryPath = strApplicationPath + "/Information Documents/";
DirectoryInfo di = new DirectoryInfo(strXLStoredDirectoryPath);
string fileName = flUpldSelectFile.FileName;
if (!File.Exists(strXLStoredDirectoryPath))
{
Directory.CreateDirectory(strXLStoredDirectoryPath);
di.Attributes = FileAttributes.Normal;
}
string strCreateXLFileDestinationPath = strXLStoredDirectoryPath + fileName;
if (File.Exists(strCreateXLFileDestinationPath))
{
File.Delete(strCreateXLFileDestinationPath);
}
flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath);
di.Attributes = FileAttributes.ReadOnly;
}
catch (Exception)
{
throw;
}
}
please guide.........
-***********************************************************************
Still problem there . it is not resolved . getting UnauthorizedAccessException. as access denied to deleting file. I m tired now . please help; I tried many things..please help
-***********************************************************************
Is may be iffect of VSS ? i am using that
UPDATE:
Part of your issue might be what is saving/creating this file. If you're using a built in "Save" or "SaveAs" feature the underlying file stream might still have a lock on the file. writing your own save logic with a FileStream wrapped in a Using statement will help dispose the stream right when you're done thus allowing you to further manipulate the file within the same context.
if flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath); is the only logic that saves the file then get rid of the built in SaveAs functionality. write your own save logic using a FileStream wrapped in a Using block.
In your example i can't see what flUpldSelectFile is so i am assuming it is a System.Web.UI.WebControls.FileUpload control. Here is an example of rolling your own save logic.
using (FileStream fs = new FileStream(strCreateXLFileDestinationPath, FileMode.Create))
{
byte[] buffer = flUpldSelectFile.FileBytes;
fs.Write(buffer, 0, buffer.Length);
}
As stated previously, use this tool to find out if there is a lock on the file by another process.
ORIGINAL
Pop open this wonderful tool and search for that file to see who/what has it locked
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
(source: microsoft.com)
If your code is working under IIS , Note that ASPNET user doesn't have access to computer files, you should give access to it, that is not recommended, or store you files in the place where ASPNET user have access
see here
Try a combination of these 2 steps:
Set the IIS application pool to run under an account with privileges such as a domain account or local user account (not a default account like local service or local system). Instructions for IIS7.
Turn impersonation on in the web.config file, in the <system.web> section:
<identity impersonate="true"/>
<identity impersonate="true" userName="contoso\Jane" password="password"/>
I think the message is clear, you do not have authorization to delete the file or it is opened by another application. I bet 2$ you can't delete the file manually either.
As others have said, this is because IIS runs your application as a user with restricted access rights. This is a wise security precaution, so that your system is less vulnerable to malicious attacks.
What you need to do is to give the ASPNET user access to the specific folder. You do that from the security tab in the properties of a folder. The user you need to give full control to depends on the version of IIS you are using. In Windows XP it is ASPNET. In Windows Server 2003, 2008 and Windows Vista, 7 it is NETWORK_SERVICE.
See also this question for more details.
Make sure the file isn't opened or
locked by another user/process.
Make sure ASPNET user has access on the file\folder (check the file\folder's property using windows explorer and go to security tab. check if ASPNET user is added there).
One of two things are happening. Either the file is already open, or the permission of the user running IIS does not have the proper permissions.
Either way, this utility ProcMon: Proc Mon
will help you determine the issue. Run ProcMon, kick off your process to try and delete the file. Then go back to procmon. Hit Ctrl-E to turn off the capture, then Ctrl-F to find. Enter the name of the file you're trying to delete. Then once you've found the correct line with the access denied (or similar error) Double click on the the line to get further information. When you click on the Process tab, it will show you the exact user that is trying to delete the file.
So, if it is a file permission issue, you now know the exact user, and can therefore go to the file system right click on the folder that houses the file you are trying to delete, and grant that user permissions to read/write/update that folder.
Second, if the file is locked open instead of a permissions issue, you will have to find out what process is holding open the file. If you are also writing this file in another part of your code, perhaps you are not closing it properly or releasing the object reference.
Have you verified that the file does not have the read-only attribute set?
I don't think we have enough info to be helpful. What is the security context (identity) during the call to Delete? Is the application impersonating the end user? If it is, how are they authenticated? If by Windows / Active Directory, then you'll need to verify that user's access rights to the specific file. If by Forms login, then you should probably not impersonate and verify that the AppPool's security context has the appropriate access rights.

Access denied to path , when uploading image to folder in server

Am getting error when you are going to upload the file on specified folder in the server. Here I am going to upload P6100083.jpg in storeimg folder. When I am going to upload I am getting the following error:
Access to the path 'C:\inetpub\vhosts\bookmygroups.com\httpdocs\storeimg\P6100083.jpg' is denied.
Can anyone help me... How to use permisiion and were to use...
My code is while uploading image
if (FileUpload1.HasFile)
{
float fileSize = FileUpload1.PostedFile.ContentLength;
float floatConverttoKB = fileSize / 1024;
float floatConverttoMB = floatConverttoKB / 1024;
string DirName = "storeimg";
string savepath = Server.MapPath(DirName + "/");
DirectoryInfo dir = new DirectoryInfo(savepath);
// string savepath = "C:\\Documents and Settings\\ssis3\\My Documents\\Visual Studio 2005\\WebSites\\finalbookgroups\\" + DirName + "\\";
if (fileSize < 4194304)
{
string filename = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(filename).ToUpper();
if (extension.Equals(".jpg") || extension.Equals(".JPG") || extension.Equals(".JPEG") || extension.Equals(".GIF"))
{
savepath += filename;
FileUpload1.SaveAs(savepath);
}
}
}
Thanks in advance
I have no success making my upload or any write operation on filesystem work on IIS7.
Still getting the error: Access to the path is denied.
My AppPool is running under Network Service. I have granted all kinds of accounts Full Control (Network Service, Network, IIS_IUSR, Administrator, Users, Everyone), restarted the webservice several times, studied all IIS7 settings, googled for two hours and nothing works.
IIS7 and WS2008 s-u-c-k-s. Sorry for the term. Anybody can help?
I just wanted to add: I noticed that in the upload's destination folder's Properties there's this checkbox named "Read-only (Only applies to files in folder)" and it's checked. It cannot be unchecked, comes back checked after unchecking and clicking the OK button. Is that IIS7 guarding it?
Editing this message to add the SOLUTION: My admin has turned off the silly UAC "the security confirmation feature" on our server, restarted the machine and it works now. No "write" access rights for "Network Service" or any other IIS-used account was needed. When accessing the file system in a ASP.NET web application using the integrated authentication and having the impersonation set to true in its web.confing, the file system seems to be accessed by the authentified end-user's account, not by the Network Service account which the AppPool is running under. (Many people tell you to set Network Service permissions, but that is not true.) So you need to set the "write" permissions for your end-users (usually domain users: "DOMAIN\domain users") on your particular folder.
Oh yea, and the "Read-only (Only applies to files in folder)" checkbox mentioned above does not seem to have any effect. However Microsoft says "some programs might have problems writing to such folder and you should use command line statement "attrib -r -s" to get rid of the Read-Only attribute" -- but it won't work. It will stay there checked-grayed. But don't worry about that. Microsoft becomes more and more silly every day.
Indead, it's a server issue.
You need to verify if the user underlying your application pool has write access to the directory.
If you use IIS7, you have a new feature that helps you give custom write to this user and dun need to change the user.
Look at this link:
http://www.adopenstatic.com/cs/blogs/ken/archive/2008/01/29/15759.aspx
Hope this helps.
This is a server issue. Make sure you have the necessary rights to write files.
Btw, since you call ToUpper() on extension there's no reason to test for ".jpg".
If you are using Plesk Panel, go to file manager of Plesk Panel. List files and folders inside "httpdocs". Each file and folder has a lock icon at the very right. Click that of "storeimg" folder to change permissions. Click advenced button. Give full permission to these:
Plesk IIS WP User (IWPD_214(your_login_name))
Plesk IIS WP User (IWPD_214(your_login_name))
And click OK.
First you check the permission is enable or not if not then go to that folder which folder has to be use for containing files then right click on folder then there will be display folder properties then click on security there will be display multiple number of user which user have to be permit then click allow that all permission will be activated.
First, make sure your code runs fine locally (I assume that something you've already done).
Then deploy to your TEST or UAT environment. If you're having issue there, then this is a configuration issue. Make sure the service account under which your website's app pool is running has access to the folder.
Please make use of C# method Path.Combine() to build up your path and avoid issues with leading or trailing / and \.

Categories