c# starting a .exe file from current file path + folder + exe file - c#

Im trying to have a exe file opened on click, its going to be in a subfolder of a file path, I dont want to put in c:\folder due to file install will be different for each user, I would like to use file path + another folder in that file path to + "file.exe"
Any ideas?

you can use this code smple
static void Main(string[] args)
{
Process.Start(<"your file path");
}
for example if you wish to run notepath++ then
you path will be=#"C:\Program Files (x86)\Notepad++\Notepad++.exe

Related

How to determine if C# executable is being run from zip file?

I'm trying to ensure that users of my C# .NET Core program always unzip it before running, however, I can't seem to find a good solution for this.
I tried using Assembly.GetExecutingAssembly().Location and checking if it contained Temp but it did not work as intended. My understanding is that when running an executable within a zipped file, Windows will automatically unzip (?) to a temp directory and then proceed.
Any ideas on how to go about doing this?
Thanks!
One solution might be that you put another file beside the exe file inside the zip file and make the exe find for this file in the same location of the exe.
When an exe is executed from inside a zip, the unzip program will unzip the exe but not the other file and checking for this file you can test whether just the exe was unzziped or if the whole files where unzipped and the guess it was installed.
(Anyway, I agree with Ian Kemp, as it seems to be an XY problem)..
I can think of two checks that will work in many cases. Obviously, these checks are not bullet-proof.
Most .zip viewers will extract the clicked .exe in a temporary folder.
Windows Explorer zip folder view runs the .exe from a temporary folder and sets the ReadOnly attribute.
Sample app
using System;
using System.IO;
namespace SimpleApp
{
class Program
{
private static bool IsLikelyRunFromZipFolder()
{
var path = System.Reflection.Assembly.GetEntryAssembly().Location;
var fileInfo = new FileInfo(path);
return fileInfo.Attributes.HasFlag(FileAttributes.ReadOnly);
}
private static bool IsRunFromTempFolder()
{
var path = System.Reflection.Assembly.GetEntryAssembly().Location;
var temp = Path.GetTempPath();
return path.IndexOf(temp, StringComparison.OrdinalIgnoreCase) == 0;
}
static void Main(string[] args)
{
var isTemp = IsRunFromTempFolder();
var isZip = IsLikelyRunFromZipFolder();
Console.WriteLine($"Run from TEMP folder? {isTemp}");
Console.WriteLine($"LIKELY run from Windows Explorer ZIP folder? {isZip}");
Console.ReadKey();
}
}
}
I disagree with the sceptics in this thread. Running an exe from a "zip folder" in Windows Explorer is indeed a common source of error. By showing a warning, inexperienced users could get some immediate advice.

File ReadAllText is getting a wrong path (C#)

I have a local project that in the future will be in a pipeline.
Because of this, I need to use a relative path to get and read a json file.
But using the File.ReadAllText I'm obtaining the following answer:
> File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default)
System.IO.FileNotFoundException: Could not find file 'C:\Users\15071\MyJsonFiletoRead.json'
Note that 'C:\Users\15071' is not the project folder, this is my windows user folder.
My struct is here:
C:\Projetcs\MyProjectTest -->> Project folder
C:\Projetcs\MyProjectTest\MyClass.cs -->> The class where I'm calling the ReadAllText
C:\Projetcs\MyProjectTest\MyJsonFiletoRead.json -->> My json file that I'm trying to find
I have tried the following commands to check my PATH, but all answer is wrong:
> Environment.CurrentDirectory
"C:\\Users\\15071"
> Directory.GetCurrentDirectory()
"C:\\Users\\15071"
AppDomain.CurrentDomain.BaseDirectory
"c:\\program files (x86)\\microsoft visual studio\\2019\\community\\common7\\ide\\commonextensions\\microsoft\\managedlanguages\\vbcsharp\\languageservices\\DesktopHost\\"
Has somebody a solution to fix this?
Note: If I use the full path, it works:
File.ReadAllText("C:/Projetcs/MyProjectTest/MyJsonFiletoRead.json", Encoding.Default)
If the file is located at the same folder of your executable file, you just need to pass the file name:
File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default);
If the file is located at a relative path from the folder where your executable file is located, you can get the Assembly Location and combine it with a relative path:
var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\..\\MyJsonFiletoRead.json");
File.ReadAllText(path, Encoding.Default);
You need to find the current folder and then read the file
var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
File.ReadAllText(currentFolder + "/MyJsonFiletoRead.json")

My program stop when it saves files on the directory (inside the app directory) after creating the setup by inno setup Compiler?

On my project I have instructions that save Excel Files in a folder called "Ficheirs" inside the Project bin\debug directory (bin\debug\fichiers) using: Directory.GetCurrentDirectory() + "\Fichiers" to set the path to that , it works well before creating the setup
However after creating the setup using inno Setup Compiler , and eventually adding the folder "Ficheirs" while creating the setup , my program doesn't work
How to fix that so that my program keeps saving my excel files on that folder ?
Directory.GetCurrentDirectory() + "\Fichiers"
This is a very unreliable function to set a path to a directory.
Without testing, the application can work in a different directory at the time you are asking for GetCurrentDirectory().
e.g the working directory of the setup / App at the moment you run GetCurrentDirectory()
App\
App\bin\
App\bin\debug\
GetCurrentDirectory()+ "\Fichiers" returns
D:\Programs\App\Fichiers
D:\Programs\App\bin\Fichiers
D:\Programs\App\bin\debug\Fichiers
You should force at install all needed Dirs
Here is an example of a [Dirs] section:
[Dirs]
Name: "{app}\bin"
Name: "{app}\bin\debug"
Name: "{app}\bin\debug\Fichiers"
inside C#
Test before writing
try
{
// Set the current directory.
string target = Application.StartupPath + "\\bin\\debug\\Fichiers";
if (!Directory.Exists(target))
{
Directory.CreateDirectory(target);
}
// Change the current directory.
Environment.CurrentDirectory = (target);
..............
Setup iss
[Code]
var
excelPath : String;
..............
excelPath := ExpandConstant('{app}\bin\debug\Fichiers');

Adding content files to and accessing content files from a web service

I want to include an XML file in the bin directory of my web application/web service. I've included the bin folder in my project in Visual Studio and added the file. I set its Build Action to "Content" and Copy to Output Directory to "Copy Always". When my code goes to find it, I use
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!dir.EndsWith(#"\")) dir += #"\";
to get the directory and return it as appPath, where appPath is (unescaped version):
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\vs\0c7655f\d4908928\assembly\dl3\5cf9fd67\fdc52284_ffa7d201\
then I append the file name of my XML file (where string filename = "myXmlFile.xml") to read it:
StreamReader reader = new StreamReader(appPath + filename);
But I get an exception on that line of code, that it could not find my file. I am handling for escaping of the slashes fine, so it is not that. When I checked the physical directory that the path points to, it was not copied to that directory, and that is the cause of the exception. So how do I get my file to get copied there?
How about using HostingEnvironment.ApplicationPhysicalPath
var dir = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin\\filename.xml")
See related question how to get the application path in asp.net?.

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);

Categories