Reputation:
I want to create a web service that takes a text file as parameter and returns the content of that file.
This web service will then be used by a C# client.
This is what I have so far (webservice):
[WebMethod]
public String txtFile(String filename)
{
StreamReader sr = File.OpenText(filename);
{
String line = sr.ReadToEnd();
return line;
}
}
and(client):
WebService ws = new WebService();
ws.txtFile("textfile.txt");
When I run the client I get UnauthorizedAccessException.
Upvotes: 1
Views: 15683
Reputation: 13030
If you're running the web service in IIS the web service doesn't magically run as your user. Unless you have Windows Authentication turned on for your application, the web service will access files using the Application Pool Identtity and that identity must have permissions to the file.
Upvotes: 1
Reputation:
So the issue was that the current IIS user didn't have permission to access the file (not even read).
And apparently the web service will use Application Pool Identity and not the current (windows)user (unless you have Windows Authentication turned on for your application).
Follow these steps to add permission for application pool:
Upvotes: 2
Reputation: 63105
you sending only the file name, then how service check your local file from server by the file name!
You need to give full path to file name, like network path or file server path. and that path should be accessible for the web service running user.
but if you change the method as below and send the file content with file name you can save it to server.
[WebMethod]
public void Upload(byte[] contents, string filename)
{
var appData = Server.MapPath("~/App_Data");
var file = Path.Combine(appData, Path.GetFileName(filename));
File.WriteAllBytes(file, contents);
}
Upvotes: 2
Reputation: 44605
Add some logging in your web service, and dump to the logging framework the input parameters and the exception details ( yes, you should add a try-catch in the web service ).
before you do this:
StreamReader sr = File.OpenText(filename);
also check:
if(!File.Exists(filename))
{
// dump to the log file the file was not found at the location... filename
return string.empty;
}
then you can do:
using(var sr = File.OpenText(filename))
{
string line = sr.ReadToEnd();
return line;
}
finally, mind the fact that passing a relative path from the client to the server does not mean anything, you should probably verify that only a network path can be specified, the C or D drive or any other locally mapped drive/path in the calling client might be not accessible or access something different on your web server.
Upvotes: 1
Reputation: 28385
File.OpenText
can throw many different exceptions: http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx (I'd start by making sure the path is in the right format)
StreamReader.ReadToEnd
can throw an OutOfMemoryException or an IOException. See reference here: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx
Upvotes: 0