Allow write permissions for .NET application - c#

I've been running in circles with allowing my application to write to a folder on a shared network drive.
So far I have this:
FileUploadControl.SaveAs(Server.MapPath("myFolder/" + filename));
this successfully saves the file to
\\machineName\inetpub\wwwroot\myApp\myFolder
However, I am also trying to save the same file to a folder outside of the root folder on the path
\\machineName\myFolder
using:
FileUploadControl.SaveAs("C:\\myFolder\\" + filename);
This returns an error of "Access Denied." So how do I go about allowing my application to write a file to \\machineName\myFolder? I have tried giving write permissions to IIS_IUSRS and NETWORK SERVICE to no avail. Should I create a user with privileges to write to the network drive and then use impersonation to use that user when writing to the drive?
Using IIS 7 with .NET 4 application.

Go to your application's app pool, right click on it and choose Advanced properties. Check the Identity value under Process model settings group. Give this Identity permissions to write files in your folder.
If the value is ApplcationPoolIdentity than user name is IIS APPPOOL\app_pool_name.

Related

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));

WPF app writes files/data into "C:\ProgramData" but fails to write into other folders

We have developed WPF application which allows user to select folder path. WPF application writes files/data into this selected path. When we select "C:\ProgramData" as the path, it creates the file and write the data. But when the path is other than "C:\ProgramData", file is generated but data is not written into the file and it seems a permission issue. Can anybody help us in finding out , how we can assign the same kind of permission to selected folder same as "C:\ProgramData" so that it allows to write data into the file. In conclustion what is the extra permission does "ProgramData" has which is not their for other folders?
Note: it only works properly with ProgramData folder.
Whenever your application is launched with standard user rights, it can write to only those folders to which a standard user can write to. E.g. are:
C:\Users\USERNAME\
C:\ProgramData\
D:\
It will not be able to write to folders like:
C:\
C:\Users\SOME_OTHER_USERNAME\
c:\Windows
C:\Windows\System32 etc
For that you either need to disable UAC or launch the application with administrative permissions.
I would suggest that whenever user selects a folder from your application check if you can create a file/ folder in that location before accepting the path.
solution what i can give is let's user select the path after you get the folder path just check whether you can write data to it , see this code
bool HasAccessToWrite(string path)
{
try
{
using (FileStream fs = File.Create(Path.Combine(path, "Access.txt"), 1, FileOptions.DeleteOnClose))
{
}
return true;
}
catch
{
return false;
}
}
#Ganesh is right but you may go with one of the following options:
Run the installer with admin rights, ask user to select target folder during installation and set the permissions to everyone or required groups of users/roles.
If above is not applicable then configure your application to always run under admin account, in that way it will have access to all folder to write data. To configure run as admin user application manifest as explained here:
Turn off UAC, not a recommended approach though.
I had same issue so, I forced installer to be run under admin rights and asked user to create target folders during installation. Used a custom action to set full rights for everyone user group on the target folder. Since security was not issue for us so, it was ok to allow everyone but consider your environment before using this option.

dowload file from shared drive to desktop C#

I'm trying to download a file from shared drive to desktop but it keeps throwing an error that its not a virtual path. Here is my code:
if (Directory.Exists(Server.MapPath("M://SharedDrive//" + username)))
{
File.Copy("M://SharedDrive//" + username, "C:\\Documents and Settings\\user\\Desktop\\" + username, true);
}
Are you doing this from in an ASP.NET application? (I'm guessing since you are using Server.MapPath). Then you have two problems:
IIS runs in the service session, which has no access to the users' mapped drives such as M:. IIS can only access physical drives, or UNC paths (the latter requires security to be set up correctly).
IIS has no access to a user's desktop.
Please explain a bit more detailed what you are trying to achieve if we are to be able to help.
If you copy file to/from network location, you should login or impersonate user.
Check these;
Copy file on a network shared drive
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/ffebef9c-a063-46e6-8307-2f73bbf688b7/

file upload C# asp.net

i am trying to upload files in asp.net and putting a specific path to be saved. windows user.
it is outputting me an error :
System.UnauthorizedAccessException was unhandled by user code
Message=Access to the path 'C:\Users\USER\Desktop\fyp2\CMS TEST4\CMS\CMS\Upload' is denied.
my code is:
var guid = Guid.NewGuid();
if (File.HasFile)
{
var length = File.PostedFile.FileName.ToString().Length;
var ind = File.PostedFile.FileName.ToString().IndexOf('.');
var sdfs=guid.ToString()+File.PostedFile.FileName.ToString().Substring(ind, length - ind);
File.PostedFile.SaveAs("C:\\Users\\USER\\Desktop\\fyp2\\CMS TEST4\\CMS\\CMS\\Upload");
}
The ASP.NET worker process does not have access rights to that path. By default I believe IIS worker processes run under the Network service account. You can either add write rights for the folder to this account, or set up a new Application Pool with a different identity (i.e. a user that does have write rights).
As simple as the error puts it, your application requires the folder to have proper write permissions.
I'm asuming this is a Web Application. In that case, you'll need that the user which IIS uses to run applications has Write permissions over the specified folder.
The users directory is fairly locked down. If the account the web server is running under is not the specified user, it will not, by default, have access to the path. You can either grant explicit access to that path to the account running your web server, or create a folder with appropriate permissions external to that path and create a link on the user's desktop.
Looks like current user has not permission to save. Before writing try use FileSystemRights with AccessControlType.Allow to know permission info of the destination.

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