Antoine Gautier
Antoine Gautier

Reputation: 653

Running external executable from C# solution with relative path

I get a Win32Exception File not found when trying to run an external executable (with dependencies) from a C# solution with the following code.

public static string TestMethod()
{
    try
    {
        Process p = new Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = Path.Combine("dist", @"test.exe");
        p.Start();
    }
    catch (Exception ex)
    {
        expMessage = ex.Message;
    }
    return expMessage;
}

Remarks:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="dist"/>
    </assemblyBinding>
  </runtime>
</configuration>

EDIT The only solution proposed in Specifying a relative path which actually works in this case is the one eventually provided as a comment by Viacheslav Smityukh combining AppDomain.CurrentDomain.SetupInformation.ApplicationBase to reconstruct the absolute path. However there seems to be a potential issue at runtime as stated in Pavel Pája Halbich's answer below. From How can I get the application's path in a .NET console application? I found out another solution based on Mr.Mindor's comment using the following code:

string uriPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string localPath = new Uri(uriPath).LocalPath;
string testpath = Path.Combine(localPath, "dist", @"test.exe");

Now I wonder which one is the proper way considering a future deployment of the solution with Window Installer.

Upvotes: 0

Views: 1479

Answers (2)

Connor
Connor

Reputation: 897

The path to dist in your case is the current working directory, which isn't aligning with your expectations.

Try changing your path to:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dist", @"test.exe");

Upvotes: 1

Pavel P&#225;ja Halbich
Pavel P&#225;ja Halbich

Reputation: 1583

You need to specify full path to that executable. So you can use System.Reflection.Assembly.GetExecutingAssembly().Location resulting in

Path.Combine(System.IO.Path.GetDirectoryName( iSystem.Reflection.Assembly.GetExecutingAssembly().Location), "dist", @"test.exe");

As you can se in this question How can I get the application's path in a .NET console application?, using AppDomain.CurrentDomain.BaseDirectory could work, but it is not recommened - it could be changed in runtime.

EDIT corrected answer for getting directory instead of full location to executable.

Upvotes: 0

Related Questions