简体   繁体   中英

.NET WCF service can not access local file

After looking at many topics I decided to ask this

I have a WCF service that reads a file from the local file system. When the service is tested locally on my computer it was no problem doing that.

But when I publish the service in IIS8 i am getting this error

The system cannot find the file specified

I have tried creating a new user and new ApplicationPool that uses that identity to run the service and also given full control to the folder that is trying to be read but the problem continues.

I have also tried even using the Administrator as the identity of the new Application Pool but did not solve the problem either

What am i missing ?

Assuming that you have a relative URL and the account that is running the application has the proper permissions, you're probably not getting the correct pathname to your file.

You can try something like this to find the full path of your file:

using System.IO;

public FileInfo GetFileInfo(string filename)
{
    if(filename == null)
        throw new ArgumentNullException("filename");


    FileInfo info = new FileInfo(filename);

    if(!Path.IsPathRooted(filename) && !info.Exists)
    {
        string[] paths = {
                    Environment.CurrentDirectory,
                    AppDomain.CurrentDomain.BaseDirectory,
                    HostingEnvironment.ApplicationPhysicalPath,
                    };

        foreach(var path in paths)
        {
            if(path != null)
            {
                string file = null;
                file = Path.Combine(path, filename);

                if(File.Exists(file))
                {
                    return new FileInfo(file);
                }
            }
        }
    }

    throw new FileNotFoundException("Couldn not find the requested file", filename);
}

It's returning an instance of System.IO.FileInfo but you can easily adapt it to return a string (full pathname).

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