How to save XML file on IIS 7 server using ASP.NET - c#

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)

Related

Access Denied in .NET writing file to file share

I have a web service that is trying to write a file to a file share.
The application pool for the site in iis is running as a custom domain account: "domain\domainaccount"
I'm operating under the assumption and hope that when the code tries to write the file it will use the "domain\domainaccount" user to do so.
Executing the following line of code produces the error: Access to the path [filename] is denied
FileStream stream = File.Create(fileName, result.Length);
I have confirmed that the "domain\domainaccount" account has access to [filename] which is the full path of the file including the file name. I have even given the account access from the very top of the share structure, not just the specific folder the file needs to be written to. In fact, if I run notepad as "domain\domainaccount" I can save a file to that exact location.
What might I be doing incorrectly? Is it not using the domain account to write the file? If not, can I change something so that it does?
I should note that if I log into the iis server and run the web service from there, I do not get the access denied message and the file is created.

Check if file from remote server exists

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

How to save the XML files in Computer?

In my project my app receives an XML from another program. I want to save this XML file in the folder in my PC. But if there is another XML file that will come, the XML will be added in the folder not overwrite the existing XML. How can I achieve it?
I am using this code right now but I don't know why I got an access denied error.
System.IO.File.WriteAllText(#"C:\XML", abc);
First of all, the error that you receive is because of Windows UAC which denies users without Administrator privileges to write on the C:\ disk. Create a folder in which you have access, for example "c:\temp\" and write your files in there.
Also, you specify a file and not folder.
And if you don't want to overwrite the file, just make sure to generate a unique filename (a guid perhaps).

WP8 copy SharedStorge file directly into IsolatedStorage

I am developing a Windows Phone 8 application but am having a lot of issues with file access permission exceptions hindering the approval of my application when ever I try accessing files in the "local" folder (this only happens after the application has been signed by the WP store, not when deployed from Visual Studio). To solve this I have moved all file operations to IsolatedStorage and this seems to have fixed the problems.
I only have one problem left though. My application needs to make use of the file extension system to open external files and this seems to involve the file first being copied to the local folder where after I can then manually copy it into IsolatedStorage. I have no problem in implementing this but it seems that a file access permission exception also occurs once the system tries to copy the external file into the local folder.
The only way I think this can be solved is if I can direct the system to directly copy into IsolatedStorage but I cannot figure how to do this or if it is even possible. It seems as if though the SharedStorageAccessManager can only copy into a StorageFolder instance but I have no idea how to create one that is directed into IsolatedStorage, any ideas?
PS. Do you think that the Microsoft system might be signing my application with some incompetent certificate or something because there is not a hint of trouble when I deploy the application from Visual Studio, it only happens when Microsoft tests it or when I install it from the store using the Beta submission method.
Below is a screenshot of the catched exception being displayed in a messagebox upon trying to open a file from an email:
EDIT:
Just to make it even clearer, I do NOT need assistance in figuring out the normal practice of using a deep link uri to copy an external file into my application directory. I need help in either copying it directly into isolatedstorage or resolving the file access exception.
Listening for a file launch
When your app is launched to handle a particular file type, a deep link URI is used to take the user to your app. Within the URI, the FileTypeAssociation string designates that the source of the URI is a file association and the fileToken parameter contains the file token.
For example, the following code shows a deep link URI from a file association.
/FileTypeAssociation?fileToken=89819279-4fe0-4531-9f57-d633f0949a19
Upon launch, map the incoming deep link URI to an app page that can handle the file
// Get the file token from the URI
// (This is easiest done from a UriMapper that you implement based on UriMapperBase)
// ...
// Get the file name.
string incomingFileName = SharedStorageAccessManager.GetSharedFileName(fileID);
// You will then use the file name you got to copy it into your local folder with
// See: http://msdn.microsoft.com/en-us/library/windowsphone/develop/windows.phone.storage.sharedaccess.sharedstorageaccessmanager.copysharedfileasync(v=vs.105).aspx
SharedStorageAccessManager.CopySharedFileAsync(...)
I've inline the information on how to do this from MSDN http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987(v=vs.105).aspx
Read that documentation and it should be clear how to use the APIs as well as how to setup your URI mapper.
Good luck :)
Ok I figured it out. The "install" directory is actually restricted access but for some reason the Visual Studio signing process leaves the app with enough permissions to access this folder. The correct procedure of determining a relative directory is not to use "Directory.GetCurrentDirectory()" but rather to use "ApplicationData.Current.LocalFolder". Hope this helps!

Denied acces to a file

I have a code which is similar this:
string file;
using (StreamReader r = new StreamReader("xml.xml"))
{
file = r.ReadToEnd();
}
XElement xml = XElement.Parse(file);
using (XmlWriter w = XmlWriter.Create("xml.xml")) //The point of problem!
{
w.WriteStartDocument();
...;
w.WriteEndDocument();
}
When I try run it like a console application is everything all right. But problems start when I want to use it in an ASP.NET application. At the using line it throws UnauthorizedAccessException exception with a description "access to the path is denied". Why?
You need to check which account your application Pool is using to access your server files/folders, for example, make one code to copy one file to application folder, check all security info, copy and paste on this problem folder, normally use this account "IIS_IURRS" give full control to test only...
If IIS/the web server is configured correctly, an account with a very limited set of permissions is used. As your path points to the application directory, it is very likely that the application pool account is not allowed to write to this location.
If you run the code in a console application, your user's permissions are applied and it is more than likely that you are allowed to write to the output folder of the project as Visual Studio writes the build output there under your account.
I would not recommend to change the application pool account or the permissions of the application folder in the file system - it is a very sensible limitation that limits the amount of trouble an attacker can possibly make.
Therefore I'd recommend to either move the file to a folder that the account can write to without changing permissions or define a special one outside of the application folder hierarchy that the account is given permissions to.
Also keep in mind that multiple users might access the file at the same time, so a database might be a better choice to store the data.

Categories

Resources