简体   繁体   中英

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

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?

var serverPath =
       System.Web.Hosting.HostingEnvironment.MapPath("~/filefolder/myfile.txt"); 
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;

Have you tried using HostingEnvironment.ApplicationPhysicalPath ?

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

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.

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");

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM