views:

54

answers:

4

I'm trying to use Controller.File to return a FilePathResult from a view in my ASP.NET MVC 2 project. I use it like this:

return File(pdfFilePath, "application/pdf", "foo.pdf");

However I keep getting this error in the yellow screen of death:

The process cannot access the file [the file path] because it is being used by another process.

This error usually comes up when you forget to close a file stream, but I figured that this should be taken care of by the ASP.NET MVC framework. This doesn't happen every time, but rather periodically. Sometimes I get the file just fine but then it just stops working. I am using the development server when testing this.

Any ideas?

A: 

Do you have the file already open when you get this message?

If you do it might be Adobe locking the file.

Simon G
I do not have it open. This happens to other files as well, such as images.
Deniz Dogan
A: 

The likeliest scenario is that something other than ASP.NET / IIS has the file open. Have you ensured that no other processes have a lock on the file when this error occurs?

If you have access to the server when the error happens, you can use a tool like Process Explorer to view what exactly is locking the file.

Ryan Brunner
Using Process Explorer I find that the only time I cannot access the file is when devenv.exe (or more specifically WebDev.WebServer.exe) aquires the file. Whenever it does not do that, I can download it just fine. Now all I need to do is figure out why this is?
Deniz Dogan
+1  A: 

Are you accessing the file prior to the line of code you provided? If so, how are you accessing it?

When accessing files, try to use the following to avoid file stream conflicts:

File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

The last enum FileShare.ReadWrite will allow other file streams to read and write to the file even if you have it open. Of course, it is better to remember to close your stream ASAP.

http://msdn.microsoft.com/en-us/library/y973b725.aspx

Baddie
To anyone having the same problem: I opened the file in another part of the code using `FileMode.Open` without ever closing it.
Deniz Dogan
A: 

The locking can occur from within asp.net itself - as asp.net displays thread-agility, and as such it may be another thread from within the asp.net threadpool completing the request. This would be why you only see this issue intermittently. Baddie's answer is basically the solution to your problem. As an aside, you might find other issues if you're using resources that contain state that are declared as threadstatic. If this is the case you might want to look at making use of CallContext.