create network folder C# - c#

I have 2 machines EX001 and Ex002 on domain booleanarray.com.
I have credentials of a domain user , (username ABC and password pwd123) to log on to EX002 on domain booleanarray.com.
There is a folder C:\EWS on EX002.
I want to write a C# Windows application that runs on EX001 and creates a new folder under the folder C:\EWS\ on Ex002.
C:\EWS is not a shared folder, but is accessible by ABC when user ABC logs on to EX002.
Can anyone suggest how can I create such a new folder on different computer on same domain in C#?

I won't be able to give you detailed answer. But you probably can first authenticate your windows application on other machine 2 in the domain. Probably you can use ConnectionOptions object. Then you probably can send the command for creating directory to remote machine.

If c:\ews is not a shared folder, I believe you would need to do it via the administrative share. So something like:
String path = #"\\EX002\c$\EWS\";
Directory.CreateDirectory(path + "new folder name");
As the name implies though, this requires that the account have administrative access to EX002.

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

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.

Set write permission on folder create

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".

Can you make a C# program which can not access to any local file system other than the folder it is installed?

Let me ask whether you can make a C# program which can not access to any local file system other than the folder/sub folders it is installed? And how if the answer is yes.
For details if it is necessary and possible, users are supposed to accept the program runs under a special user account which is restricted the file access only to the folder it is installed and to sub folders.
Thank you very much in advance.
Edit : Let me add context. I want users do not change their accounts. And as a programmer I do not have complete control over the program for some reasons.
Can you make a C# program which cannot access any part of the local file system other than the directory in which it is installed?
No, because every C# program will need to at the very least have access to the .NET runtime libraries, which are in the Windows install directory.
My suggestion to you is that you look into isolated storage. The .NET code access security system enables you to set a policy which states that certain programs only get to access the .NET runtime, the installed location of the code, and a special "isolated storage" directory that can be used for the application to store per-user data.
The answer is yes, but how you do this is complicated.
First, you need a user account with extremely limited permissions. It must be able to access files and run programs within the installation directory of the program, and that's pretty much it. You can create such a user with the installer program, using tools in the System.DirectoryServices namespace. Here's an example of creating a user:
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
private void CreateUser(string userName, string password)
{
DirectorySearcher dseSearcher = new DirectorySearcher();
string rootDSE = dseSearcher.SearchRoot.Path;
string userDSE = rootDSE.Insert(7, "OU=Users,");
DirectoryEntry userDE = new DirectoryEntry(userDSE);
DirectoryEntry user = userDE.Children.Add("CN=" + userID, "user");
staff.Properties["samAccountName"].Value = userID;
staff.Properties["UserPrincipalName"].Value = userName +
#"#domain";
staff.CommitChanges();
staff.Properties["userAccountControl"].Value =
ActiveDs.ADS_USER_FLAG.ADS_UF_NORMAL_ACCOUNT |
ActiveDs.ADS_USER_FLAG.ADS_UF_DONT_EXPIRE_PASSWD;
staff.CommitChanges();
staff.Invoke("SetPassword", new Object[] { password });
}
Now, once that's happened, you need to make sure your program normally runs in the context of that user account. You can do that by specifying the user account to run the program with in a ProcessStartInfo object, used by a "bootstrapper" program that is what you create shortcuts for. You can then also ensure the program is running in the context of that user account using Environment.CurrentUser, and abort execution of the program if it is being run by any more permissive account.
If you just want to restrict the program to a particular account, you can look up the user's credentials, and exit the program if it's not the right one.
http://msdn.microsoft.com/en-us/library/csyx45b8.aspx
http://msdn.microsoft.com/en-us/library/sfs49sw0.aspx

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.

Categories