0

I have tu publish a windows form application in c#. The problem is that I have a folder named "dati" in project folder enter image description here

In code, when I try to read from folder I use this instruction

string projectDirectory = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;

and when I try to read an xls inside this folder I have this instruction

string path = projectDirectory + "\\dati\\dati.xlsx";
        string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=NO;\"";

In debug all works perfectly, also if I execute the .exe inside bin/Debug or bin/Release folder. When I publish the application, and put it in another folder like C:\ProjectPublished I get this error because it is trying to read the dati folder from another path.

enter image description here

What I have to do? Thanks

Martina
  • 1,852
  • 8
  • 41
  • 78
  • 1
    `string path = Path.Combine(Application.StartupPath, @"dati\dati.xlsx");`, assuming `dati.xlsx` is set to, e.g., `Copy to Output Directory -> Copy if newer` and is included in the setup files. -- Never use `Environment.CurrentDirectory` or `Directory.GetCurrentDirectory`: you don't know what *current* is, the *current directory* can change at any time. If the file is an empty template, you could also embed it and create a copy in a safe path, as `Application.CommonAppDataPath`, the first time the app is started. – Jimi Nov 24 '20 at 10:01
  • If I use the Path.Combine(Application.StartupPath, @"dati\dati.xlsx") when I debug, the application try to read file inside folder D:\\Stargate\\StarGate\\bin\\Debug\\dati\\ that not exists because it's in D:\\Stargate\\StarGate – Martina Nov 24 '20 at 10:12
  • That's where it's supposed to be when you're in debug mode. The Directory you're referring to is inside the Project's Folders: you cannot have data there, as long as your executable is concerned, that path doesn't exist (and it actually doesn't exist when you deploy). – Jimi Nov 24 '20 at 10:18

2 Answers2

2

The simplest way to work with data files is to include them in the project as a content item. Use the right click your *.xlsx file in the Solution Explorer and set Build Action to Content and Copy to the output directory to Always. It will make the build engine include the data file to the /bin directory. Then you may need to set up your deploy engine to include this file in the deployable package. For instance, if you are using ClickOnce, you may need to include this file in Publish tab of your project

Nikita K
  • 406
  • 2
  • 8
0

Use this:

string projectDirectory = AppDomain.CurrentDomain.BaseDirectory ;

This will give you the directory where your executable is residing.

SQL Police
  • 4,127
  • 1
  • 25
  • 54