简体   繁体   中英

File.ReadAllLines doesn't work at webservice

I wanna do read all lines from txt file and I use to it File.ReadAllLines.

At winforms it works fine.

But, when I', trying do the same at webservice at webmethod it crash

System.IO.FileNotFoundException: Nie można odnaleźć pliku 'C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\nameOfFile.txt'.

CopyOutputToDirectory is set to copy always.

  string[] lines = File.ReadAllLines("nameOfFIle.txt", Encoding.Default)

File is in webservice folder for webservice, and in application folder for application

You need to obtain the web service root path and combine it with the filename if the file is in the root folder of your web service (where web.config file is located):

var path = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "nameOfFile.txt");
string[] lines = File.ReadAllLines(path, Encoding.Default);

In a ASP.NET (WebForms or WebService) application you need to use something like:

string filePath = Server.MapPath(@"~/nameofFile.txt");
using (var reader = System.IO.File.OpenText(filePath))
{
     ... reader.ReadAllLines();
}

Assuming that the file is in the root of your WebService.

The webservice is looking for the file at C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\ , as indicated in the error message.

CopyOutputToDirectory would copy the file to the bin directory of the compiled webservice.

You need to pass the correct path to File.ReadAllLines - if you know the exact location, pass that through (you can try HostingEnvironment.ApplicationPhysicalPath for the base directory of the webservice).

Thanks for help, but it is not good fo r situation , where class which operating on this string file is in another folder.

I have folder Webservice and folder Server(there is this class) In webservice folder i have webservice project, and in server folder i have library

(this is a way which I implementing Facade pattern)

The txt file is in server folder.

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