Running a batch file in relative path? - c#

There is a batch file which I want to run it when I press the button.
My code works fine when I use absolute (full) path. But using relative path causes to occur an exception.
This is my code:
private void button1_Click(object sender, EventArgs e)
{
//x64
System.Diagnostics.Process batchFile_1 = new System.Diagnostics.Process();
batchFile_1.StartInfo.FileName = #"..\myBatchFiles\BAT1\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = #".\myBatchFiles\BAT1";
batchFile_1.Start();
}
and the raised exception:
The system cannot find the file specified.
The directory of the batch file is:
C:\Users\GntS\myProject\bin\x64\Release\myBatchFiles\BAT1\f1.bat
The output .exe file is located in:
C:\Users\GntS\myProject\bin\x64\Release
I searched and none of the results helped me. What is the correct way to run a batch file in relative path?!

The batch file would be relative to the working directory (i.e. f1.bat)
However, your working directory should be an absolute path. It is not guaranteed whichever path is current for your application (may be set in .lnk). In particular it's not the exe path.
Sou you should use the path of your exe file as obtained from AppDomain.CurrentDomain.BaseDirectory (or any other well known method) to build the path of your batch file and/or working directory.
Finally - use Path.Combine to determine a correctly formatted path.

According to JeffRSon`s answer and comments by MaciejLos and KevinGosse my problem was solved as below:
string executingAppPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
batchFile_1.StartInfo.FileName = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1\\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(0, executingAppPath.LastIndexOf('\\')) + "\\myBatchFiles\\BAT1";
An alternative way is:
string executingAppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
batchFile_1.StartInfo.FileName = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1\\f1.bat";
batchFile_1.StartInfo.WorkingDirectory = executingAppPath.Substring(6) + "\\myBatchFiles\\BAT1";
I report it here hoping help somebody.

Related

How to Get current date and create directory Everyday in C#?

get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

Can you run an embedded .vbs file from a C# Windows Form?

I have been looking all over but cannot find a definitive answer/solution, or any solution I try fails. I am making a WinFormApp that calls an embedded .vbs file to script a program I use at work. This is what my Project Solution looks currently:
Project Solution
The test.vbs file is set as an embedded resource in its file properties. Here is the different code I have tried to use to run the script from the form:
private void button1_Click(object sender, EventArgs e)
{
string path = Path.Combine(Path.GetTempPath(), "test.vbs");
File.WriteAllBytes(path, Properties.Resources.Test);
Process.Start(path);
string path2 = Path.Combine(Path.GetTempPath(), "test.vbs");
System.Diagnostics.Process.Start(#"cscript //B //Nologo " + path2 + "");
}
Here is what my test.vbs file is:
dim thing
thing = "It did something!"
Wscript.Echo thing
The test.vbs file is primarily meant as a proof of concept to make sure I can at least run a .vbs file. The test.vbs file compiles fine outside of the WinForm.
Most of the time I receive 'The system cannot find the file specified' as the error message. I have read that it may be easier to just convert my .vbs file to C# but they are GUI scripting for SAP and all of SAP's libraries seem primarily set us for .vbs files.
I am still relatively new to C# so I may be way off with this so please tell me if I am. If there is another question that fixes my issue please link it.
Thank you for your time!
EDIT #1 Code compiles and seems to run.
string path2 = Path.Combine(Path.GetTempPath(), "test.vbs");
var startInfo = new ProcessStartInfo
{
WorkingDirectory = "" + path2 + "",
FileName = #"cscript"
};
However the script does not seem to be outputting to the cmd...
Your process start command is incorrect. Here is the correct version
System.Diagnostics.Process.Start("cscript", #"//B //Nologo " + path2 + "");

Retrieve filepath for selenium webdriver

I am trying to upload a file with the sendkeys function on the inputid.
I am currently using the path C:\Users\myusername\Documents\seleniumsolution\Utils\Dir\Dir1\Dir2\Dir3\UploadFolder\example.jpg
I see the file in my solution. But I dont want to give to complete path but only the filename and that selenium finds the path itself. Otherwise I will be the only one that can use this testcase.
I tried with:
var file = Path.Combine(Directory.GetCurrentDirectory(), url);
And tried with:
string documents = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"UploadFolder");
Both of them dont give me the required result.
Hope that you guys can help me out.
You might need to travel on the folders tree to get to the file
AppDomain.CurrentDomain.BaseDirectory
will get you in the bin\debug folder. From there you can use parent to move up to the file location. For example (might need some tweaking)
string solutionParentDirectory = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.Parent.Parent.FullName;
string file = Path.Combine(solutionParentDirectory, #"UploadFolder\example.jpg");
You can also try
string file = Path.GetFullPath("example.jpg");

How to display chm file in c# winforms application

I have added .chm file to my application root. when i fetch the file using below code it is referencing the path to bin/release/somehting.chm
System.Windows.Forms.Help.ShowHelp(this, Application.StartupPath+"\\"+"somehting.chm");
i want to get the path relative to installation location of application. please help.
the chm file added to the root directory is not loading after deploying the application. its not even loading while debugging in visual studio and not giving any error.
As I can see the first code snippet from your question calling Help.ShowHelp isn't so bad. Sometimes I'm using the related code below. Many solutions are possible ...
Please note, typos e.g. somehting.chm are disturbing in code snippets.
private const string sHTMLHelpFileName = "CHM-example.chm";
...
private void button1_Click(object sender, EventArgs e) {
System.Windows.Forms.Help.ShowHelp(this, Application.StartupPath + #"\" + sHTMLHelpFileName);
}
So, please open Visual Studio - Solution Explorer and check the properties of your CHM file. Go to the dropdown box shown in the snapshot below and set "Always copy" (here only German). Start your project in Debug mode and check your bin/debug output folder. Do the same for Release mode and output folder. The CHM should reside there and I hope your CHM call works.
You need :
String exeDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
So :
String HelpFilepath = "file://" + Path.Combine(exeDirectory , "somehting.chm");
Help.ShowHelp(this, path);
Answer from similar topic is:
// get full path to your startup EXE
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
// get directory of your EXE file
string exeDir = Path.GetDirectoryName(exeFile);
// and open Help
System.Windows.Forms.Help.ShowHelp(this, exeDir+"\\"+"somehting.chm");

Write a text file to a sub-folder

I am trying to write out a text file to: C:\Test folder\output\, but without putting C:\ in.
i.e.
This is what I have at the moment, which currently works, but has the C:\ in the beginning.
StreamWriter sw = new StreamWriter(#"C:\Test folder\output\test.txt");
I really want to write the file to the output folder, but with out having to have C:\ in the front.
I have tried the following, but my program just hangs (doesn't write the file out):
(#"\\Test folder\output\test.txt");
(#".\Test folder\output\test.txt");
("//Test folder//output//test.txt");
("./Test folder//output//test.txt");
Is there anyway I could do this?
Thanks.
Thanks for helping guys.
A colleague of mine chipped in and helped as well, but #Kami helped a lot too.
It is now working when I have:
string path = string.Concat(Environment.CurrentDirectory, #"\Output\test.txt");
As he said: "The CurrentDirectory is where the program is run from.
I understand that you would want to write data to a specified folder. The first method is to specify the folder in code or through configuration.
If you need to write to specific drive or current drive you can do the following
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
string path = diveLetter + #"Test folder\output\test.txt";
StreamWriter sw = new StreamWriter(path);
If the directory needs to be relative to the current application directory, then user AppDomain.CurrentDomain.BaseDirectory to get the current directory and use ../ combination to navigate to the required folder.
You can use System.IO.Path.GetDirectoryName to get the directory of your running application and then you can add to this the rest of the path..
I don't get clearly what you want from this question , hope this get it..
A common technique is to make the directory relative to your exe's runtime directory, e.g., a sub-directory, like this:
string exeRuntimeDirectory =
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string subDirectory =
System.IO.Path.Combine(exeRuntimeDirectory, "Output");
if (!System.IO.Directory.Exists(subDirectory))
{
// Output directory does not exist, so create it.
System.IO.Directory.CreateDirectory(subDirectory);
}
This means wherever the exe is installed to, it will create an "Output" sub-directory, which it can then write files to.
It also has the advantage of keeping the exe and its output files together in one location, and not scattered all over the place.

Categories

Resources