ERROR: The SaveAs method is configured to require a rooted path
I was creating an admin page to upload a pdf to a site. I had the following code and thought it was ok. I figured that I needed a relative path to put the pdf into a folder that was within the project. I was using the following code:
1 2 3 | var newPath = Path.Combine("~\\PDFFiles\\", inputModel.ItemNumber.ToString().Trim()); newPath = Path.Combine(newPath, pdf.FileName); pdf.SaveAs(newPath); |
Well I was wrong and I kept getting the following error:
The SaveAs method is configured to require a rooted path, and the path ‘~\PDFFiles\Introductions.pdf’ is not rooted.
What was happening was that the “SaveAs” method needs to have an exact path to the folder and doesn’t know what to do with the path as it is. This was a little frustrating at first because I really would like to make this simple and not have to hard code the path for the server when it is published. After thinking about it a little the reasons do make sense. The “SaveAs” method needs to know exactly where you want to store the file. It is working on the machine itself and not in any relative location.
I searched a little to find an answer and many of them pointed to a permissions issue or that I needed to save the file to another location and then move it to where I wanted. This was really unacceptable to me. Then I found this post from Phil Haack and realized what I was doing wrong.
1 | var newPath = Path.Combine(Server.MapPath("~\\PDFFiles\\"), inputModel.ItemNumber.ToString().Trim()); |
That one change made it all work. I added the “Server.MapPath” method to get the exact path to the folder. This was the exact thing I was looking for. Simple, easy and straight forward. Thank you Phil Haack for the post and putting me on the right “path”.