Console App Get Full Path for Filename in Args - c#

So, I have a simple console app which takes one parameter: filename.
Now, when I run it like this:
program.exe "C:\Temp\list.json"
It works since I have passed a full file path.
What I want to achieve is next:
I want to CD into C:\Temp and from there I want to call a file like:
"C:\Program Files\WS\program.exe" list.json
Basically, I want to pass in only the file name and from that construct the full file path.
How is this achievable?
I tried finding out if I can get the current directory from Terminal where I am, in my case, it would be C:Temp, but I did not find any answers for that.

You can do that.
When you execute the below commands:
CD c:\TEMP
"C:\Program Files\WS\program.exe" list.json
The current directory for your program.exe would be C:\TEMP.
You can construct full path using below c# code.
//// assuming fileName contains the input file name
var fullPath = Path.Combine(Environment.CurrentDirectory, fileName);
Hope this works.
Reference: Stackoverflow Question.

Related

Why is the working directory the directory of the executable and not where I'm running from?

I'm running my console app from a plain old command prompt. I'm running it two ways:
using a relative path to the executable from what I think is the working directory. i.e.
C:\Working>.\path\to\my.exe -fileToRead file.txt
using a folder in my $PATH$. I.e.
C:\Working>my.exe -fileToRead file.txt
file.txt is in C:\Working and my.exe is C:\Working\path\to. my.exe will output an XML log file to the working directory. In my mind that, that should be C:\Working, but the file actually ends up in C:\Working\path\to. This doesn't jive with all other command line applications.
I'm not doing anything weird or non-standard (that I know about). I've tried just using the file name for the XML file, "TestResult.xml" and also Path.Combine(Environment.CurrentDirectory, "TestResult.xml"). Both end up in the executable directory, not the directory from which I'm running. The command-line parameter file argument is being read properly, so I know that's working.
Clarification: Basically, my problem is that Environment.CurrentDirectory and Assembly.GetExecutingAssembly().Location are the same directory, but shouldn't be.
What am I doing wrong here? And how do I get the directory from which I execute, not the path to the executable? (I realize I have the exact opposite problem of many questions on stackoverflow)
The results you have using Environment.CurrentDirectory are not the one I get with a very simple program like this
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Environment=" + Environment.CurrentDirectory);
Console.WriteLine("Assembly=" + Assembly.GetExecutingAssembly().Location);
}
}
}
Executing this little app from the command line gives always for the first line the directory where the command prompt is running and the second line always the directory where the assembly is located.
So, I suppose that your problem is caused by something different. Probably a change in the current directory.

How can i find the directory from where im running my program exe file?

In my project \debug directory i have the program exe file for example:
test.exe
Now once i will run this test.exe from c:\
And in the second time i will copy the test.exe to d:\ and run it from there.
In my code i have this line:
string programFilesX86 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) + "\\Diagnostic Tool\\7z.dll";
Instead the program files x86 how can i get each the directory from where im running the exe file ?
One way (sure fire way also in .Net CE) is
string path = Path.GetDirectoryName(
Assembly.GetEntryAssembly().GetModules()[0].FullyQualifiedName);
or
string path = Path.GetDirectoryName(
Assembly.GetEntryAssembly().Location);
This will prevent Shortcut's from setting the applications CurrentDirectory or StartupPath which could technically be different from it's execution path (ClickOne programs for example).
You can get the running directory by doing:
Application.StartupPath
You can read more about it here
Alternatively you can try Environment.CurrentDirectory but that may not yield you the results you want because of short cuts and other ways of getting to your file.
http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx
You can also do:
System.IO.Path.GetDirectoryName(Application.ExecutablePath);
Or
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

C# run batch file, command not recognised

I have implemeneted a method into my c# program to run a batch file, which runs a virus scan on any files uploaded;
public static Int32 ExecuteCommand(String filePath, Int32 Timeout){
Int32 ExitCode;
ProcessStartInfo ProcessInfo = new ProcessStartInfo();
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
ProcessInfo.FileName = filePath;
Process proc = Process.Start(ProcessInfo);
proc.WaitForExit(Timeout);
ExitCode = proc.ExitCode;
proc.Close();
return ExitCode;
}
Ok now my batch file;
#ECHO OFF
c:
cd "..\AVG\AVG9\"
avgscana.exe /SCAN="..\learninglounge.com.solar.quarantine\" /REPORT="..\learninglounge.com.solar.antivirus\virusReports\report.txt"
EDIT : I do have fully qualified link to avg exe and directories but have replaced here with .. for purposes of posting to stackoverflow. Sorry if this caused confusion.
So my problem is the reporting side of my batch file. I can double click the batch file and it scans and creates the report no problem. When i run it through my c# i get an exit code of 2; command not recognised. It's fine if i remove the report part of my batch file. Now obviously this points to write permissions but I have checked that and the impersonated user has write access on the directory. Is there anything Im missing?
Thanks all
The error states that avgscana.exe isn't located in directory which is set as "current" when you execute command. When you click on your bat file in Windows Explorer current directory is set to directory where bat file is located. Probably your avgscana.exe is located in the same folder so it works fine.
When you execute the command from .Net application current directory remains the same (if you haven't changed it then it will be a folder where .Net app is located). If your .Net app is located not in the same folder as bat file then you will get an error which you're actually getting. You should either specify a full path in your bat file or set Environment.CurrentDirectory in .Net app before launching bat.
HAve You checked that all enviromental variables are set exactly the same as You run the batch file from cmd line. I am pretty sure that there might be some differences. Also what kind of operating system is it. If this requires elevation (vista windows 7) You might actually need to impersonate appropriate user in code.
luke
Ok well ive done a work around, id rather have saved the report there and then but instead i just catch the standard output from the process and then save to a file + any processing.
Weird one this.
In your batch file, you have:
c:
cd "..\AVG\AVG9\"
avgscana.exe
/SCAN="..\learninglounge.com.solar.quarantine\"
/REPORT="..\learninglounge.com.solar.antivirus\virusReports\report.txt"
When the command is executed, the 'current' directory on drive C: is ambiguous. You just move up the directory tree. Same with the avgscana.exe command, you make relative references instead of absolute.
Are you certain that the CD command has brought you to the correct directory? Change the CD command to an absolute reference ( cd "c:\wherever\avg\avg9\" ), and that way you can be sure your avgscana command's relative references are found.
Your CD command may be failing silently but your avgscana.exe may be in your path, so it does get executed, but since the relative /scan and /report locations are not found, it fails with a code 2.
Good luck!

Relative path in .NET

I am running my C# application from "D:\App\program.cs". My application needs to execute a file placed in "C:\Program Files\software\abc.exe".
How can I set the relative path in my program to execute the "abc.exe"?
To answer the question how to get a path that shows the relative location of pathB from pathA. You can use the Uri class to get the relative path.
string pathA = #"C:\App\program.cs";
string pathB = #"C:\program files\software\abc.exe";
System.Uri uriA = new Uri(pathA);
System.Uri uriB = new Uri(pathB);
Uri relativeUri = uriA.MakeRelativeUri(uriB);
string relativeToA = relativeUri.ToString();
Console.WriteLine(relativeToA);
This yields "../program%20files/software/abc.exe" for the relative path.
I have changed your example from D to C though because you can't have a relative path for two locations on different drive letters, although the above code still works, just yields the absolute.
OR if the c# bit is a red herring, and as I now understand you want to run a batch file:
in batch file put:
cd c:\program files\software\
abc.exe
abc.exe will then execute from software folder and not folder of the batch file.
You shouldn't be using relative path for referring something from Program Files. I would recommend to use Environment.GetFolderPath (and Environment.SpecialFolder) to get path to Program Files and then use some config setting to get reminder path to the program.
It's not clear what you mean by "set relative path", but if you're using Process and ProcessStartInfo to run the executable, I would suggest that you use an absolute path to specify the executable, and ProcessStartInfo.WorkingDirectory to tell the process where to run (so that relative paths will be evaluated appropriately within the new process).
EDIT: If you want the batch file to run c:\Program Files\Software\abc.exe then the contents of the batch file should be just:
"c:\Program Files\Software\abc.exe"
(Note the quotes to allow for space.)
I don't see what this has got to do with relative pathnames though.
If the application is in Program Files then you can create a batch file like
"%ProgramFiles%\software\abc.exe"

Getting full path for Windows Service

How can I find out the folder where the windows service .exe file is installed dynamically?
Path.GetFullPath(relativePath);
returns a path based on C:\WINDOWS\system32 directory.
However, the XmlDocument.Load(string filename) method appears to be working against relative path inside the directory where the service .exe file is installed to.
Try
System.Reflection.Assembly.GetEntryAssembly().Location
Try this:
AppDomain.CurrentDomain.BaseDirectory
(Just like here: How to find windows service exe path)
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
This works for our windows service:
//CommandLine without the first and last two characters
//Path.GetDirectory seems to have some difficulties with these (special chars maybe?)
string cmdLine = Environment.CommandLine.Remove(Environment.CommandLine.Length - 2, 2).Remove(0, 1);
string workDir = Path.GetDirectoryName(cmdLine);
This should give you the absolute path of the executable.
Another version of the above:
string path = Assembly.GetExecutingAssembly().Location;
FileInfo fileInfo = new FileInfo(path);
string dir = fileInfo.DirectoryName;
Environment.CurrentDirectory returns current directory where program is running. In case of windows service, returns %WINDIR%/system32 path that is where executable will run rather than where executable deployed.
This should give you the path that the executable resides in:
Environment.CurrentDirectory;
If not, you could try:
Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName
A more hacky, but functional way:
Path.GetFullPath("a").TrimEnd('a')
:)

Categories