file upload C# asp.net - c#

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.

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

file copy to remote server access error

I kept getting Access error on the following code:
var fileName = "test.dgi";
var local = Path.Combine(#"C:\aaa", fileName);
var remote = Path.Combine(#"\\sw933chipqw001\tmp\", fileName);
Error I got is:
Access to the path '\sw933chipqw001\tmp\test.dgi' is denied.
I tried to give Read/Write access to IUSR, IIS_ISURS and the service account I set in the app pool. nothing worked. I'm using IIS7.
But if I add "Everyone" with the Read/Write access, it works. Anyone know what is the specific account that I need to give permission to?
Well the default account that an app pool is running in IIS7 is:
IIS AppPool\<AppPoolName>
In your case it's probably
IIS AppPool\DefaultAppPool
Here is a little bit more info.
I just tried to grant "Authenticated Users" full control on the remote folder and it works!

How can I take ownership of files with incorrect security?

I have a folder structure on a (Server 2003 SP2) file server and I need to delete it using C#. I can't do that because I get System.UnauthorizedAccessException: Access to the path '\\xyz\blah\...' is denied. (where the path points to a sub-folder) because the permissions on the sub-folder are incorrect. So, I've been trying to take ownership of the files and this fails with System.UnauthorizedAccessException: and now I'm stuck.
Detail
I have an admin tool used by users with minimal privs. They need to delete folders and files to which they don't have access, so I wrote a UI which calls a web service. The web service runs under an AppPool with a domain account which is (now) a member of Administrators on the file server, so it should have access to delete the files and folders. But some of the folders have incorrect permissions. For example, when I log onto the file server with an account in Administrators and open the security tab for the folder, I see:
And for these folders my code doesn't work.
I've given the appPool account 'Take ownership of files or other objects' on the web server using Local Security Policy. Other posts (e.g. this one) have pointed out that you need to explicitly enable SeTakeOwnershipPrivilege in code and recommended Process Privileges which I'm using in my web service:
using (new PrivilegeEnabler(process, Privilege.TakeOwnership))
{
System.Diagnostics.Debug.WriteLine(String.Format(
"Privilege:TakeOwnership status: {0}.",
process.GetPrivilegeState(Privilege.TakeOwnership)));
SetFolderOwnerToCurrentUser(folderName, groupName);
}
When I run this, I see:
Privilege:TakeOwnership status: Enabled.
(Before adding the priv via LSP, I was seeing Privilege:TakeOwnership status: Removed.)
In SetFolderOwnerToCurrentUser if I just use
var directorySecurity = new System.Security.AccessControl.DirectorySecurity();
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
System.IO.Directory.SetAccessControl(folderPath, directorySecurity);
I also get System.UnauthorizedAccessException: Access to the path '\\fs\blah' is denied. Again, it's the sub-folder it's complaining about.

Allow write permissions for .NET application

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.

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.

Categories