user5731250
user5731250

Reputation:

Get FilePath for my excel file with sheetname

I am trying to do is to get filepath for my excel file. But I am unable to do so.

File is in Document/Visual Studio 2013/Project/ProjectName/a.xlsx

string path = Path.Combine(HttpContext.Current.Server.MapPath("~/"),"a.xlsx");
string SheetName="Sheet1";

Is it wrong way to do it or is it correct way?

Upvotes: 6

Views: 456

Answers (3)

Alexei - check Codidact
Alexei - check Codidact

Reputation: 23078

Since your project is not a Web one, I expect that you some sort of Output where build process generates an executable file, some assemblies etc. You can put Build action of your Excel as Content (more details here) and use this base path to retrieve it:

System.Reflection.Assembly.GetExecutingAssembly().Location

It is important to think in terms relative to your executable (or executing assembly to be more precise), since your output will have to run outside your development environment and your excel must still be accessible.

Also, getting the exact executing assembly might be tricky in some scenarios.

Upvotes: 0

user1413
user1413

Reputation: 537

This is the better answer according to me.

Better to save in

C:\Users\AJ1110\Documents\Visual Studio 2013\Projects\Proj\Proj 

And in

program.cs

string pathfile = @"..\..\a.xlsx";
string sheetName = "Whatever_SheetName_IS!!!";

This might solve your problem.

Upvotes: 1

Frédéric
Frédéric

Reputation: 9854

HttpContext.Current does not work outside of a web context.

If your project is running inside a console or windows program, it cannot work with HttpContext.Current. MapPath is meant to translate a web path to a file system path. ~/ is a .Net convention for pointing the root web path of a web application.

You should explicit what are your requirements about how to resolve the folder containing your file.

Maybe should you simply put that in some configuration file (using settings property tab of the project by example) and retrieve it from there.

Edit:

So, from your comment on this question, it looks like you have to seek the xl file in the executing folder.

There is a number of ways for achieving this, depending on your application use cases.

By example, check this question.

Upvotes: 1

Related Questions