Is FileInfo.Copy accross network good solution? Is CAS required? - c#

Seems that everything I do involves win services copying files across servers. I seem to get a lot of security & securityaccess type exceptions and never fully understand the causes. I am wondering if fileinfo or file.copy is a good solution or if there is a better. Is there a particular attribute I should be using or something to avoid these errors? Issue is not account or password related. example are \ipaddress\sharename \ipaddress\drive\path using domain accounts.
---Added Specific example.---
- I log on to serverA as domain\username. (including domain name)
- I open file eplorer in the address bar enter \\serverB\c$\folder hit enter, I right-click, create new file. No problem.
- I install service, go to properties select Log On, This Account and set the username as domain\username (including the domain name) same password I logged onto serverA with. It accepts it no problem.
Application does a FileSystemWatcher on \\serverA and copy to \\serverB when changed to keep the config files in sync.
private void CopyNewFileToClone()
{
FileInfo OriginalConfigFile = new FileInfo(Path.Combine(ConfigurationManager.AppSettings.Get("directoryToWatch"), ConfigurationManager.AppSettings.Get("fileToWatch")));
FileInfo CloneConfigFile = new FileInfo(Path.Combine(ConfigurationManager.AppSettings.Get("directoryToCopyTo"), ConfigurationManager.AppSettings.Get("fileToCopyTo")));
FileInfo tmp = new FileInfo(Path.Combine(CloneConfigFile.DirectoryName,"~" + CloneConfigFile.Name));
OriginalConfigFile.CopyTo(tmp.FullName, true);
tmp.CopyTo(CloneConfigFile.FullName, true);
tmp.Delete();
}
When I start the service I get Service cannot be started.
System.UnauthorizedAccessException: Access to the path '\\serverB\C$\folder\filename' is denied.

I use fileinfo to copy files from servers and it seems to work fine. If your sure it's not a account or password issue I would start looking at your DNS. If the network can't resolve what account is trying to access the network folder it won't matter if you are using a valid account. You may get lucky some/most of the time with cached accounts but there is no telling when it might not work and when it will work.
I would trace the network if you are getting a lot of broadcast messages for failed responses.

This was due to Code Access Security policy. Ran
c:\Windows\Microsoft.NET\Framework\v2.0.50727\CasPol.exe -af <path\application.exe>
and error resolved.
Adding as a installation step in all apps that need to write to HD, especially accross network via unc such as \server\share\file.

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.

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

Why does System.IO.FileSystemWatcher crash my service when I try to monitor a folder in a network share? [duplicate]

I am trying to run a file watcher over some server path using windows service.
I am using my windows login credential to run the service, and am able to access this "someServerPath" from my login.
But when I do that from the FileSystemWatcher it throws:
The directory name \someServerPath is invalid" exception.
var fileWatcher = new FileSystemWatcher(GetServerPath())
{
NotifyFilter=(NotifyFilters.LastWrite|NotifyFilters.FileName),
EnableRaisingEvents=true,
IncludeSubdirectories=true
};
public static string GetServerPath()
{
return string.Format(#"\\{0}", FileServer1);
}
Can anyone please help me with this?
I have projects using the FileSystemWatcher object monitoring UNC paths without any issues.
My guess from looking at your code example may be that you are pointing the watcher at the root share of the server (//servername/) which may not be a valid file system share? I know it returns things like printers, scheduled tasks, etc. in windows explorer.
Try pointing the watcher to a share beneath the root - something like //servername/c$/ would be a good test example if you have remote administrative rights on the server.
With regards to the updated question, I agree that you probably need to specify a valid share, rather than just the remote server name.
[Update] Fixed previous question about the exception with this:
specify the name as #"\\someServerPath"
The \ is being escaped as a single \
When you prefix the string with an # symbol, it doesn't process the escape sequences.
I was just asked this question in regards to FileSystemWatcher code running as a service and the issue is permissions. I searched and found this question and answer but unfortunately none of the answers here solved the problem. Anyway, I just solved it, so I thought I would throw in the solution here for next guy who searches and find this question.
The drive was mapped as a logged in user but the service was running as LocalSystem. LocalSystem is a different account and does not have access to drives mapped by a user.
The fix is to either:
Authenticate first (I use a C# Class to establish a network connection with credentials)
Run your service as a user that has access to the share.
You can test LocalSystem authentication by using a LocalSystem command prompt, see How to open a command prompt running as Local System?
Even though this is already answered I thought I would put in my two cents worth becaus eyou can see this same error even if you supply valid paths.
You will get the same error when the process running the watcher does not have access to the remote share. This will happen if the watcher is in a service running under the System account and the share is created by a user. System does not have access to that share and wont recognize it, you will need to impersonate the user to get access to it.
although you can use a FileWatcher over the network, you will have to account for other factors, like disconnection of the network share. If your connection to the share is terminated (maintenance, lag, equipment reset, etc) you will no longer have a valid handle on the share in your filewatcher
You can't use directory watches over network shares, this is a limitation of the OS, not of .NET.

FileSystemWatcher Fails to access network drive

I am trying to run a file watcher over some server path using windows service.
I am using my windows login credential to run the service, and am able to access this "someServerPath" from my login.
But when I do that from the FileSystemWatcher it throws:
The directory name \someServerPath is invalid" exception.
var fileWatcher = new FileSystemWatcher(GetServerPath())
{
NotifyFilter=(NotifyFilters.LastWrite|NotifyFilters.FileName),
EnableRaisingEvents=true,
IncludeSubdirectories=true
};
public static string GetServerPath()
{
return string.Format(#"\\{0}", FileServer1);
}
Can anyone please help me with this?
I have projects using the FileSystemWatcher object monitoring UNC paths without any issues.
My guess from looking at your code example may be that you are pointing the watcher at the root share of the server (//servername/) which may not be a valid file system share? I know it returns things like printers, scheduled tasks, etc. in windows explorer.
Try pointing the watcher to a share beneath the root - something like //servername/c$/ would be a good test example if you have remote administrative rights on the server.
With regards to the updated question, I agree that you probably need to specify a valid share, rather than just the remote server name.
[Update] Fixed previous question about the exception with this:
specify the name as #"\\someServerPath"
The \ is being escaped as a single \
When you prefix the string with an # symbol, it doesn't process the escape sequences.
I was just asked this question in regards to FileSystemWatcher code running as a service and the issue is permissions. I searched and found this question and answer but unfortunately none of the answers here solved the problem. Anyway, I just solved it, so I thought I would throw in the solution here for next guy who searches and find this question.
The drive was mapped as a logged in user but the service was running as LocalSystem. LocalSystem is a different account and does not have access to drives mapped by a user.
The fix is to either:
Authenticate first (I use a C# Class to establish a network connection with credentials)
Run your service as a user that has access to the share.
You can test LocalSystem authentication by using a LocalSystem command prompt, see How to open a command prompt running as Local System?
Even though this is already answered I thought I would put in my two cents worth becaus eyou can see this same error even if you supply valid paths.
You will get the same error when the process running the watcher does not have access to the remote share. This will happen if the watcher is in a service running under the System account and the share is created by a user. System does not have access to that share and wont recognize it, you will need to impersonate the user to get access to it.
although you can use a FileWatcher over the network, you will have to account for other factors, like disconnection of the network share. If your connection to the share is terminated (maintenance, lag, equipment reset, etc) you will no longer have a valid handle on the share in your filewatcher
You can't use directory watches over network shares, this is a limitation of the OS, not of .NET.

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