tags:

views:

677

answers:

5

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.

A: 

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

Conrad
A: 

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.

Galilyou
How does one grant access to hosted files?Especially if those files are to be uploaded through your web application?
slightlyannoyed
Grant access to a folder on the server and upload your files to this folder, this is easy if the hosting server is yours; otherwise user HttpWebResuest/Response as suggested by DoctaJonez
Galilyou
A: 

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);
Kev
+1  A: 

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;
    }
DoctaJonez
Thanks for your suggestion Docta, i'll give that a bash.So my ASP.Net process doesn't have rights to the files in my hosted directory. Great.My intention was to also upload files to this directory, but it seems i won't have write access either. Any Idea's
slightlyannoyed
If you haven't got permissions for the directory and don't have server admin rights, I would perhaps think about storing the files in a database. This would eliminate any access permission problems that you face, although you might have DB size restrictions to consider. Reading and writing files isn't a good idea from within ASP, for example you can't clean up if it crashes (so you could end up with half written sales order files, etc...). At least with SQL you can keep integrity via using transactions, that way if it crashes you don't get half written data hanging around.
DoctaJonez
It all depends upon your requirements though. I'm guessing that you are just after making a simple application for yourself, so going down the Database route might be a bit of overkill.
DoctaJonez
Thanks for your help Docta.It seems this is going to be the best way to achieve what i'm trying to achieve.On a side note though, I've decided to go ahead with an FTPWebRequest to store and to download files from my web directory. A work around for now but it should do the trick.
slightlyannoyed
You're welcome, I'm glad I managed to help :-) Good luck with your project.
DoctaJonez
A: 

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

Rashmi Pandit