Tutorial :C#: How can Server.Mappath read a file?



Question:

I have a Visual Studio 2008 solution that contains a handful of projects. One project contains a WCF Service I'm deploying. That WCF Service references some code in one of the other projects. That code is trying to read a file that's in a folder in the WCF project. Pseudo-project structure:

Solution   Project1    myclass.cs      string file = Server.Mappath("");       Project2    filefolder      myfile.txt  

What is the correct syntax to put in the Mappath? I've tried all different variations such as:

".filefolder/myfile.txt"  "/filefolder/myfile.txt"  "./filefolder/myfile.txt"  "~/filefolder/myfile.txt"  

None seem to be able to reach the file. One thing I thought of: Visual Studio 2008 runs the project and WCF in its own sandbox in IIS. Could that be the issue? Would it work if setup and deployed in regular IIS?


Solution:1

var serverPath =         System.Web.Hosting.HostingEnvironment.MapPath("~/filefolder/myfile.txt");   


Solution:2

Have you tried using HostingEnvironment.ApplicationPhysicalPath?

var fileInfo = new FileInfo(      Path.Combine( new DirectoryInfo( HostingEnvironment.ApplicationPhysicalPath ).Parent.Name , @"filefolder/myfile.txt" ) );  


Solution:3

Server.MapPath(Path.Combine( new DirectoryInfo( HostingEnvironment.ApplicationPhysicalPath ).Parent.Name , "Filename.txt" ));  

Seems to work for me. I did need to include

using System.Web.Hosting;  


Solution:4

The best thing would be to not do this to begin with.

Why would you want to tie the deployment location of one project to the deployment location of another? If you need the WCF service to read the file, then copy the file to the WCF service.


Solution:5

From MSDN; Because the path parameters in the following examples do not start with a slash character, they are mapped relative to the directory that contains the example file.

Try:

Server.Mappath("filefolder/somefile.file");  


Solution:6

The problem is that when invoking the WCF, the file system runs all the way out to the bin/Debug folder. So trying to MapMath from there doesnt work. Backtracking up the path worked:

filedata = File.ReadAllBytes("../../filefolder/myfile.txt");  

That worked. Thanks for all the help guys!


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »