i have an application which requires access permission to a file on remote server.
My app is in Server A, and the file i want to access is in Server B. These 2 servers are in the same domain.
I created a virtual directory in Server A for the directory in Server B. The name of virtual directory is FolderFromServerB and its path is \ServerB\Folder. I use a user for auth, and when i test the connection in IIS it says all is OK.
Also, when i put an anchor tag in a test file like below, i can access the file and the content is shown in the page:
Test file --> **This works**
But my problem is when i use code in order to if that file exists or not, it always returns with False. My code is like below:
FileInfo fi = new FileInfo(#"\FolderFromServerB/test.txt"); --> This doesn't work
Response.Write(fi.Exists); --> This always 'False'
I granted 'Full Control' permission to my user& NETWORK SERVICE & Everyone & Administratos in Server B but i didnt work neither.
How can i make it work?
It was working last week. I guess the server updated itself and some updates made that occur, but i couldn't find any workaround. Im so desperate now and i have to change all of my code and spend much time to make it work.
I found the workaround that is in web.config :
<identity impersonate="true" userName="{domain}\{username}" password="{password}"/>
I used File.Exist() for a few months, but then suddenly it was gone and didnt work, and i dont know why. But it is the solution above.
Your code does not work because the current execution folder of an ASP.Net application is not the folder of you application, but c:\windows\system32.
When you create the FileInfo object, you will try to read c:\windows\system32\FolderFromServerB\test.txt.
The <a href="FolderFromServerB/test.txt"> works because the link will be relative to the current page (it won't works if the page is in another directory).
If the file you are looking for is under your application directory, you can convert a virtual to a physical path using :
string actualFilePath = HttpContext.Current.Server.MapPath("~/FolderFromServerB/test.txt");
FileInfo fi = new FileInfo(actualFilePath);
Related
Im having trouble with writing files to remote directory via network. The following code fails when I try to check if the directory exists:
if (!Directory.Exists(processingPath))
Directory.CreateDirectory(processingPath);
processingPath is composed like
processingPath = xxxObject.serverPath + "processing\\";
xxxObject.serverPath contains something like this
\\machineNetworkName\sharedFolder\
Its working properly, but when many requests are processing (running as tasks asynchronously), it stops working and failing into exception:
System.IO.IOException: The network path was not found.
Could you please help me what could be the problem and why it is failing after some time on network path???
Thanks for your solutions
I got the same error before, it was about authentication problems.
You have to be sure that you set properly the user on IIS, because it use a Default App Pool's identity which can't access to your NFS.
You can also use IIS virtual folders to set the identity.
(on IIS manager, see App Pool settings -> Identity and also virtual folders settings -> identity).
In my case, it worked better by using the Impersonation directly in the code, so I recommend you to use the VladL WrappedImpersonationContext Object: How to provide user name and password when connecting to a network share
Last thing to check, the owner of the files on your NFS server, if they were created under the root user, it might not work.
I had the same problem and solved it. The problem in my code and I see it in yours, too, is that you have the slash at the end of the network path.
Instead of processingPath = xxxObject.serverPath + "processing\\"; write: processingPath = xxxObject.serverPath + "processing";
So I have a problem in my ASP.NET MVC application, it doesn't want to save the xml file after I publish it. I have a form which I post to a controller using ajax, and then I use that data to create an xml file which i then want to save.
I use the following code to generate my xml file and save it:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);
StreamWriter path = new StreamWriter(Server.MapPath("/"+ fileName + ".xml"));
xmlDoc.Save(path);
If I run my application in debug It writes the file to ~/MySolution/MyProject/MyFile, no problem.
So when I publish the app to the IIS 7 server on my computer and load the app through localhost/MyApp, I expect it to write the file to C:\inetpub\wwwroot\MyApp\MyFile but it doesn't.
I have enabled permissions to the folder inetpub and all the subsequent folders for NETWORK SERVICE. But the AJAX post keeps returning in Error and the file doesn't appear in the folder, so I assume it's not allowing to write the file to the specified path, or the path is incorrect, ether way I don't know how to check what's gone wrong.
How do I make the published app write the xml file to the C:\inetpub\wwwroot\MyApp\MyFile path?
First of all it's not recommended to write any files in the root folder as writing to root folder cause appdomain to recycle after certain number of writes (default is 15) causing session loss. See more details here.
I would suggest you to add a path of your server to web.config and then fetch it in your code.Use something like below in the appsettings section of web.config
<add key="filePath" value="C:\inetpub\wwwroot\MyApp" />
Regarding the permissions please add Users group to your folder and give that group full permission (read/write).
To further find out which specific user (as there are too many use cases) is used by w3wp you can use process monitor as explained below
Capture Process Monitor log while reproducing issue
Filter on Access Denied
No Access Denied, so filter on w3wp.exe
Look for access to 401-3.htm
Review entries before the 401-3.htm to determine what file was accessed last
Check permissions based on successful QuerySecurityFile operation for last file accessed (in this case was asp.dll)
trying to upload a file to an already created folder but this error keeps coming
Access to the path 'C:\Users\Joe\Documents\Visual Studio
2015\Projects\training\Site1\Site1\Content\ProductImages' is denied.
and then below is this
Exception Details: System.UnauthorizedAccessException: Access to the
path 'C:\Users\Joe\Documents\Visual Studio
2015\Projects\training\Site1\Site1\Content\ProductImages' is denied.
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and
the configured application pool identity on IIS 7.5) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in File
Explorer, choose "Properties" and select the Security tab. Click "Add"
to add the appropriate user or group. Highlight the ASP.NET account,
and check the boxes for the desired access.
Source Error:
Line 73: var path = Server.MapPath("~/Content/ProductImages"); // guardo en la variable path la direccion donde quiero guardar las imagenes, este path es un string que tu lo conformas segun el interes, puedeser upload/nombre_fichero/fecha/etc
Line 74: string pathdir = Path.Combine(path, imageName);
*Line 75: file.SaveAs(path); // store file*
Line 76: var imagen = new Image();
Line 77: imagen.ImagePath = pathdir;
and line 75 is in red
When checking the granted rigths there is no restriction for storing or in the file to be stored
The security is coming from the OS, not the compiler. Navigate to your folder in Windows, right-click, change security.
If deploying, be sure to use a folder that is automatically granted write permissions to .NET - like the User/Appdata/Roaming folder.
EDIT:
You are saying you've added EVERYONE to the folder and given them full control but are still getting no joy. Please try this test:
private static void writeText()
{
using (TextWriter tw = new StreamWriter(#"C:myTestFile.txt"))
{
tw.WriteLine("Hello World",false);
tw.Close();
}
}
Run the above from your solution, then check you DEBUG folder for your solution (I've forgotten at this point if we're dealing with console or form or web, so you may have to search your computer for the mytestFile.txt file after running).
The point in running this is that C: (with no backslash) points to your project folder and will automatically have adequate permissions for write. If this works and you get a mytestFile.txt after running, then we go in one direction. If you get an access error, we go in another direction. So please run in your solution or a new console app (your solution would be best) and report back with the results. Have patience buddy - we'll do the best we can to get you where you need to be!
When you host an application in IIS, IIS will run the application under another user name depending on your application pool settings. It is a good idea to know the Application Pool (What is an IIS application pool?), but in your specific case, you do not have to go through the learning curving.
The easiest way is to figure out the actual user name IIS is using by printing out the System.Environment.UserName and grant this user to the directory you want it to access.
The file permission error is coming from your Windows OS Explorer.
It gives you the exact fix:
To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
Give this a shot.
Try to check the Sharing type of the folder.
Right click->Properties->Sharing Tab->Click Share... Buttong->Then Choose Everyone then add Then change it to read and write.
Then test your program again.
if error still exist try to add the folder to your solution explorer.
Click Solution Explorer->Show All files->Then Find the folder where it was then Include in the project.
Just give it a try.
We have to give write permissions to "IIS_Users" for folder "ProductImages" which are trying to upload, since IIS used this user to access your upload folder.
Please see here how to add IIS_Users to your folder.
Hope this helps you.
Check the permission of that folder, right click on the folder, remove selection from the check box next to "Read Only", then click on "Security" => "Edit" => Select "Users" and tick the check box for "Full Control" and "Apply"
I want to read file names of pdfs from a folder on a network share that match certain parameters and provide a link to view them on a details page for my model. All I need to get is the file name. I don't need any file management/read/write at this time.
I'm able to display a .pdf in the browser if I have the path (IE will open "file://" links). The part I'm missing is getting file names from the remote (but same domain) directory at run-time.
We've set up a virtual directory for the app to use and that has worked fine in the past if the resolved physical folder is on the same server, but that is not the case here.
I've tried Impersonation, but that doesn't seem to work as I'm still getting an access is denied error.
I realize this would probably be a security issue and is why it isn't allowed, but is there an IIS configuration or other avenue that needs to be set-up to allow this? I can't seem to find a way with just code that opens the directory for reading.
Example code of how I might normally read some info from one file in a virtual directory:
// This example code is inside a controller action, so Server refers to HttpContextBase
var path = Server.MapPath("~/MyVirtualDirectory/" + fileName);
var fileExists = System.IO.File.Exists(path);
var fileLastModified = System.IO.File.LastWriteTime(path);
To enumerate over matching files in a directory, I've used DirectoryInfo
var pdfFileNames = new List<string>();
var dir = new DirectoryInfo(Server.MapPath("~/VirtualDirectory/"));
var pdfs = dir.EnumerateFiles("*.pdf");
foreach (var pdf in pdfs)
{
pdfFileNames.Add(pdf.Name);
}
As I mentioned, these methods work fine when the physical folder is on the same server, but once the directory is on a remote drive, then it no longer works. I have permissions to open the desired directory and my collegue said he gave the appropriate permissions to the virtual directory and server. Not sure what else to try at this point.
Edit: Now that it is working, I display the files using the Virtual Directory
http://server/appName/virtualDirectory/pdfFileName
By default, IIS application pools run under a specific local Windows identity named IIS APPPOOL\[NameOfYourAppPool]. This is a local user and it will not be possible to grant permissions to this identity to access resources located on a different machine.
If both servers are inside the same domain, you can try the following solutions:
Run the IIS application under a domain user and grant the required permissions to this domain user.
Run the IIS application under the NetworkService identity and grant permissions to the DOMAIN\MACHINENAME$ account of the IIS server.
I have the following code:
var saveFolder = Path.Combine(Properties.Settings.Default.DropBoxFolder, guid.ToString("N"));
// Create folder, if it does not exist (for the first attachment, it shouldn't exist)
if (!Directory.Exists(saveFolder))
{
Directory.CreateDirectory(saveFolder);
}
var saveFilePath = Path.Combine(saveFolder, file.FileName);
file.SaveAs(saveFilePath);
I'm using GUIDs to generate folders for uploads on my IIS server. The .NET web application is configured to impersonate the user. I granted modify permissions to the target folder (it is a local path on the web server) for Domain Users, Local Service and Everyone, but some users still can't upload files. I can and other people on my team can.
The weird part is that the exception says this:
Could not find a part of the path 'C:\Users\USERID\Desktop\FILENAME'
That path is the path to the file the user selected to upload (their local file path). I feel it is safe to say that the user has permission to his own file on his own desktop. I don't use user impersonation much, so I am wondering what I missed in my configuration or permissions. Any suggestions for debugging this issue? Thanks!
Note: the CreateDirectory method works just fine, even when the exception is thrown. I would have thought that if the user didn't have permission the directory creation would have failed first.