jason jason - 1 month ago 23
C# Question

Getting a directory path using project directory

I have a project whose name is Myproject.Application.DataExporter. I'm saving a file to a directory whose name is Export. I'm using this code :

workbook.Save(@"D:\workspace\MyApp\Myproject.Application.DataExporter\Export\Calc.xlsx");


I see how to get current project directory in Stackoverflow. There is this code :

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;


I want to save file under Export directory, using a generic path like the code above. It gives current project directory. I want to use it for adding a file to Export directory. How can I use it in my project for adding a file to Export? Thanks.

Answer
string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string path = Path.Combine(dir, "Myproject.Application.DataExporter", "Export");
string file = "Calc.xlsx";
workbook.Save(Path.Combine(path, file));

or if you want to skip Myproject.Application.DataExporter

string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string path = Path.Combine(dir, "Export");
string file = "Calc.xlsx";
workbook.Save(Path.Combine(path, file));