Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program crashes when run not from own directory

Tags:

c#

path

xml

A basic question:

I have a C# Windows application which runs fine when executed from its own directory, by typing

program1.exe

but when I execute it from another directory giving full path like

d:/progs/myprog/program1.exe

it crashes. And I really need to do it this way :)

I suppose it is connected to reading some files by the program which are in the same directory. My suspected line is:

using (XmlReader OdczytywaczXML = XmlReader.Create(@"config.xml"))

Can it be the problem? I wouldn't like to give full paths to files as I'd like my program to work anywhere just by copying the files.

Oh, and I have no idea how to simulate such condition (running from another directory) while debugging - is it possible?

like image 929
RRM Avatar asked Oct 28 '25 10:10

RRM


2 Answers

You should detect your program location and construct full path to config.xml in this case, for example:

var filePath = Path.Combine(
    Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
    @"config.xml");

To simulate condition, go to project properties, page "Debug" and set Working Directory.

like image 51
max Avatar answered Oct 31 '25 02:10

max


This is surely the problem. You can add directory information on that line. In WinForms you can use Application.StartupPath for example.

In General you can use System.Reflection.Assembly.GetExecutingAssembly().Location

like image 25
Ole Albers Avatar answered Oct 31 '25 00:10

Ole Albers