1

I have a web page that is displaying a PDF file with the following code:

Response.Clear();
strFilePath = Server.HtmlDecode(Request.QueryString["filename"]);
Response.ContentType = "application/pdf";
Response.WriteFile(strFilePath);

The filename got from Server.HtmlDecode() is "\FileServer\shared\faxqueue\fax.pdf"

However an exception is thrown for directory not found and it says that it cant find the file. It also says in the exception that it is looking for: "C:[Website Root Folder]\FileServer\shared\faxqueue\fax.pdf"

This means that it has appended the filename given to the folder where the website code is located.

How can I stop it from using the website root?

Thanks

1 Answer 1

1

That is true because you ask it to do so.

It is a bad idea to pass in the direct file name using the query parameters.

You can of course create a direct path to the file you are using instead of this relative path:

string absolutePath = Path.Combine(@"C:\yourRootFolder", strFilePath);
Response.WriteFile(absolutePath);

But as said, I warn you for the security risks! You have to grant the IIS application pool user access to the folder you specify here. Your files can be easily hijacked by passing in something like:

..\..\..\Windows\anysecurefile.txt
Sign up to request clarification or add additional context in comments.

5 Comments

Would this still work if I am using a UNC path instead of a mapped drive?
OK I have used path.combine, and I break before Response.WriteFile is run and strFilePath contains exactly the filepath I need. However when the writefile is run the exception is thrown and it has added the website folder in front of my string instead of using just what was in strFilePath
Which exception? The same as above? Did you pass in the right string to the WriteFile?
I get a DirectoryNotFoundException - I check that strFilePath is correct before writefile is called, and then writefile is called passing strFilePath as a parameter. The exception message then says it couldnt find a part of the path [website folder]\strFileName. could this be something to with using a UNC path so it think I am saying use the current folder then the filename given? (like it does in Unix)
OK I found the error - I was setting the filename using the verbatim (@) operator with two backslashes for the UNC path. when I increased the number of slashes to 4 it worked, so I think it was stripping one of the slashes so it thought I was using the root folder. anyway thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.