0

I am using c++/winrt within a WinUI3 project and I am trying to have the application pull up a text file where users can select an option from it. The file I am trying to reach is in the project folder and included in the project. Currently, I have the file path set to my device so it pulls the text file from my directory. I want the application to be able to read from the program files instead of the long file path that is currently coded. I tried to change the relative path of the file and used the fstream function to read the file. I also tried just using "Aircrafts/Aircrafts.txt" but that did not work either.

Here is a snippet of the code.

fstream aircraftFile;
string info;

void MainWindow::loadPlatformData()
ifstream aircraftFile; //File Object for list
aircraftFile.open("C:\\Users\\TimmyK\\Documents\\GitHub\\sentinel3\\Sentinel3\\Aircrafts\\Aircrafts.txt", ios::in);
  • To get a fully qualified path name relative to the executing module, call [`GetModuleFileName`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamew), strip the filename portion, and append the relative part. – IInspectable Feb 26 '22 at 00:47
  • Are you creating a Win32 application or a UWP application? – Chuck Walbourn Mar 03 '22 at 04:17

1 Answers1

0

My guess is that you are writing a UWP project which is why the full-path access to your file fails. UWP's have restricted access to the file system per Microsoft Docs.

For a UWP project, you mark the file as Content Yes in the file properties so it's placed into your application's layout package. Normally the 'current working directory' is pointing to your packaged program's installed location. You can get a full path to this directory using:

auto installdir = Windows.ApplicationModel::Current().InstalledLocation();
std::wstring str = installdir.Path().c_str();

For Win32 "classic" desktop applications, there's no specific packaging or installation solution so there's lots of different ways to do it. In Visual Studio when you start the debugger or run a program, the "current working directory" is going to be the project directory but if you run the EXE from the command-line, it will be in a different directory.

To find the running EXE's directory per IInspectable, use GetModuleFileName:

wchar_t exePath[MAX_PATH] = {};
DWORD nc = GetModuleFileNameW(nullptr, exePath, MAX_PATH);
if (nc > MAX_PATH || nc == 0)
{
    // Error condition
}

A typical pattern is to look in the EXE folder, then 'walk up' the directory to find asset files. This is what we do a lot in DirectX samples for Win32. See FindMedia.

Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81