johnDisplayClass
johnDisplayClass

Reputation: 269

System.UnauthorizedAccessException on a simple ASP.Net File.IO operations

In ASP.NET (hosted) I need a simple file IO operation to read data out of a file and then force a download. Its really that simple.

I keep getting a System.UnauthorizedAccessException when executing the following code:

System.IO.FileStream fs = 
      new System.IO.FileStream(path, System.IO.FileMode.Open);

Locally it works fine, but when i upload to the shared hosting account i get the above exception.

Whats strange is that in the browser if i enter the full path to the file, i can see and use the file.

Upvotes: 2

Views: 4305

Answers (5)

Rashmi Pandit
Rashmi Pandit

Reputation: 23808

You should use IsolatedStorage for your file operations.

What Is Isolated Storage?

Running code with limited privileges has many benefits given the presence of predators who are foisting viruses and spyware on your users. The .NET Framework has several mechanisms for dealing with running as least-privileged users. Because most applications have to deal with storing some of their state in a persistent way (without resorting to databases or other means), it would be nice to have a place to store information that was safe to use without having to test whether the application has enough rights to save data to the hard drive. That solution is what isolated storage is designed to provide.

By using isolated storage to save your data, you will have access to a safe place to store information without needing to resort to having users grant access to specific files or folders in the file system. The main benefit of using isolated storage is that your application will run regardless of whether it is running under partial, limited, or full-trust.

You can refer to IsolatedStorageFileStream

Upvotes: 1

Doctor Jones
Doctor Jones

Reputation: 21664

As everyone else has mentioned, this is most likely because the ASP process hasn't got security permissions to access the file directory.

If you can access the file via your browser perhaps you could read the file by using a HttpWebRequest rather than File.Open.

This would make sense if you don't have admin control over the server.

Here's some sample code for using HttpWebRequest incase it'd help:

    /// <summary>
    /// Submits a request to the specified url and returns the text response, or string.Empty if the request failed.
    /// </summary>
    /// <param name="uri">The url to submit the request to.</param>
    /// <returns>The text response from the specified url, or string.Empty if the request failed.</returns>
    protected string getPageResponse(string url)
    {
        //set the default result
        string responseText = string.Empty;

        //create a request targetting the url
        System.Net.WebRequest request = System.Net.HttpWebRequest.Create(url);
        //set the credentials of the request
        request.Credentials = System.Net.CredentialCache.DefaultCredentials;

        //get the response from the request
        System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
        //get the response code (format it as a decimal)
        string statusCode = response.StatusCode.ToString("d");

        //only continue if we had a succesful response (2XX or 3XX)
        if (statusCode.StartsWith("2") || statusCode.StartsWith("3"))
        {
            //get the response stream so we can read it
            Stream responseStream = response.GetResponseStream();
            //create a stream reader to read the response
            StreamReader responseReader = new StreamReader(responseStream);
            //read the response text (this should be javascript)
            responseText = responseReader.ReadToEnd();
        }

        //return the response text of the request
        return responseText;
    }

Upvotes: 1

Kev
Kev

Reputation: 119806

What is the path you are passing in the path variable? You say that if you put the path into your browser and you can access the file, then this suggests that the path contains http://.... To use System.IO.FileStream you need to pass a path that has a drive letter or a UNC path.

Perhaps you should be doing:

// if file is in root of site...
string path = Server.MapPath("/myfile.txt"); 
// or if file is in /myfiles folder    
string path = Server.MapPath("/myfiles/myfile.txt"); 
System.IO.FileStream fs = 
      new System.IO.FileStream(path, System.IO.FileMode.Open);

Upvotes: 0

Ahmed
Ahmed

Reputation: 11393

Your asp.net applications run under the security context of a user named ASPNET, so in order to access any resource on your system, this user must be granted access to these resources.

Upvotes: 0

Rad
Rad

Reputation: 8381

You problem is probably that the ASP.NET process needs access rights to the path specified.

Upvotes: 0

Related Questions