Read files from where the console app shortcut is placed - c#

I am creating a console app which reads all files from the folder the exe is placed in. I basically want to place the exe in a folder which has the files, run it, and have it read all the files in that folder.
Unfortunately, I am using a few nuget packages, so I have about 10+ other .dll files, along with appsettings.json file etc.
I am having to copy all these .dlls along with my .exe file to the folder which contains the files I want to read in order to run it.
Is there a way to copy over just the exe file to the folder which contains the files and run it? (I tried this, but my console was closing straight away)
Since above didn't work, I was thinking I could create a shortcut of the .exe and just place that in the folder which contains the files. But that seems to be looking for files in the folder which contains the original .exe
Below is my code
var folderPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
var filePath = Directory.GetFiles(folderPath, "*.csv", SearchOption.AllDirectories);
foreach (var filePath in filePaths)
{
Console.WriteLine($"Reading file {filePath}");
using (var reader = new StreamReader(filePath))
using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture))
{
records = csvReader.GetRecords<Player>().ToList();
}
}

The executable must be placed where its dependencies are.
Executing an executable via a shortcut does not "change" the path where the process is running. The process still lives where the original executable has been launched.
You could consider two workarounds to solve this:
Copy or move those files on the executable workspace.
Use absolute paths instead of relative paths based on executable location.

Use cmd file instead of shortcut:
pushd %~dp0
Full-Path-to-exe\Program.exe

Related

Why does File.Copy not copy files when running on certain devices?

I wrote a program that copies all files from a certain folder to a folder on the C: drive, and it works perfectly fine on my own PC. But when I run it on another computer, it seems to only copy some of the files, and leaves the rest.
The stuff that I'm copying is in the same directory as the executable, but in a subfolder called "misc".
It collects all file directories in a string array, and uses File.Copy to copy them.
Here is the code that I have:
// Create directory
Directory.CreateDirectory("c:\\subtool\\Controller");
string dest = "c:\\subtool\\Controller\\";
// Get all files from the misc folder
string[] files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace("\\subtool.exe", "") + "\\misc");
// Cycle through all files in the misc folder and copy them to destination folder "dest"
foreach (string path in files)
{
System.IO.File.Copy(path, dest + Path.GetFileName(path), true);
}
When I run it on my main PC it runs fine, no errors. It also works when running outside of Visual Studio. However, when I run it on my laptop, it doesn't copy the files. What is this caused by?

How to find file in project folder in windows form app

I have windows form application and i have some text files in folder as in image. How can i reach them and read that files?
I also tried code below but get error value cannot be null. parameter name stream
Assembly asm = Assembly.GetExecutingAssembly();
StreamReader reader = new StreamReader(asm.GetManifestResourceStream("NexoClientApp.JsonRequests.Login.txt"));
string jtext = reader.ReadToEnd();
Thanks
be sure to copy the files while building!
See the properties of your text files like in this example:
(copy if newer will also work fine)
If you want the files to be installed as files in the destination system by keeping the project structure, you need to read them as disk items, and create a setup or simple zip that copy these files to restore the project structure for needed items.
To read them, in case of the executable is generated in bin folder as by default for every VS project:
var lines = File.ReadAllLines(RootFolderPath + #"JsonRequests\Login.txt");
public string RootFolderPath
= Directory.GetParent
(
Path.GetDirectoryName(Application.ExecutablePath.ToLower()
.Replace("\\bin\\debug\\", "\\bin\\")
.Replace("\\bin\\release\\", "\\bin\\"))
).FullName
+ Path.DirectorySeparatorChar;
We remove the debug or release folder to get the project/app root path to be able to read the desired file.
If the binary is generated in another folder, use it. If in the root itself, use it as-is. If you change to have the save folder for release and debug, adapt that.
In WinForms, all methods to get the executable path returns a path having by default debug or release... but here we need the root path of the project or installed app.
Here we don't set copy files to the executable folder in the solution explorer, but we keep the project structure on disk.
You can also create a ressource file to embbed the files you want and use GetManifestResourceStream or use the #FalcoAlexander answer to copy files in the executable folder and read from there.
string dir = AppDomain.CurrentDomain.BaseDirectory;
//OR
string dir = Application.StartupPath;
string login = File.ReadAllText(dir+"/JsonRequests/Login.txt"); //read some file
//OR
List<FileInfo> files = new DirectoryInfo(dir).GetFiles().ToList(); //get all info about files in root dir

How to move two folder back

I have file in my application on root directory.
When I'm using below code:
string startupPat = System.IO.Directory.GetCurrentDirectory();
It's taking also ...\bin\Debug\
How to move avoid this?
working code:
string test= File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrent‌​Directory(), "..\\..\\test.txt"));
\bin\Debug is the default folder your program will be compiled into. If you run your program from Visual Studio this will most likely be the current directory. Anyway, when you copy the program to another folder, the System.IO.Directory.GetCurrentDirectory() should return that folder.
For your file you have to set copy to output directory to always in the properties in order to copy the file to where your program will be.
For all files that live in the same directory as your program does you do noth need any paths, you can just use the relative file names
var textReadFromFile = File.ReadAllText("myfile.txt");

How to get the filenames with the extension os .xsd from the Project

I am having a project which is named as myfirstproject.In that I am having .cs files .xsd files .rpt files and .config files etc.Here I need to get the filename of .xsd files,if it is example.xsd,I need to get the example file name in one datatable.Like that all the .xsd file names should be filled in one datatable.The project exists in any C or D or E drive in that drive myfirstproject is the solution name and project name.In that I need to get the filenames with the extensions of .xsd.I am working with windows application.Please help me with suggestions or solution
Thanks In Advance.
Perhaps this helps:
var root = new DirectoryInfo(Path.GetDirectoryName(Application.ExecutablePath)).Parent.Parent;
var allXsdFiles = root.EnumerateFiles(".xsd", SearchOption.AllDirectories);
DataTable tblFiles = new DataTable();
tblFiles.Columns.Add("Filename");
tblFiles.Columns.Add("Directory");
foreach (FileInfo xsd in allXsdFiles)
tblFiles.Rows.Add(xsd.Name, xsd.Directory);
Maybe you need to to play around with the root folder. I have used Application.ExecutablePath to get the bin folder. Normally your project path is two parents above.
You can retrieve files from disk by using many different methods. The System.IO namespace contains many helper classes that are useful to you.
Usually you wouldn't want to read directly from your solution directory (you will read files from the executable directory, relative to the executable directory, or from a directory configured in your configuration file. Many of the methods also depend on whether you're using winforms or webforms.
The following bit of code is not something I would use in a production system, but will scan through the executable directory and pick up every .xsd file and writes it to the console, for a winforms application:
foreach (var file in System.IO.Directory.GetFiles(Application.ExecutablePath, "*.xsd")) {
System.Diagnostics.Debug.WriteLine(file);
}
Webforms / MVC would require you to swap out Application.ExecutablePath for something else.
Also, you will need to set all .xsd files to "Copy to output directory" in their VS settings.

C# console app: reference file without ..\..\filename

I need to read data from a file in a c# console application.
What works: new StreamReader(#"..\\..\myData.csv");
Problem:
the ..\\..\ work because my exe file is in the bin/Debug directory
When I deploy my project the path doesn't work any longer
Question:
How can I reference myData.csv regardless of the location of the exe file?
I had hoped to find a method that returns the 'root' of my console application
So far I tried the following:
Process.GetCurrentProcess().MainModule.FileName
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location
Path.GetFullPath("bp.csv")
AppDomain.CurrentDomain.BaseDirectory
Directory.GetCurrentDirectory()
All of these expressions lead me to the directory of the exe file not the root.
I just started to read about isolated storage but it would be nice to have something simpler. Any suggestions / recommendations?
The simplest option is probably to add your CSV file to the solution and right-click it in VS and set the build action to "Copy if newer", which will output it together with the .exe (to the Debug or Release folder) when you build.
In the code, you can get the current location of the executing assembly like this:
string folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
And then you can combine the path with the CSV file name:
string filePath = Path.Combine(folder, "myData.csv");
Where your myData.csv will be stored ? You should have an absolute location of this file.
there are couple of options
You can place this file at the same directory where your exe is placed so you will only need to do
new StreamReader("myData.csv");
you can define file location in the App.Conig file and read that location.
you can set a path variable an read the PATH variable.
You should change your code to
new StreamReader("myData.csv");
This will ensure that the data is always read from the same folder the .exe is run from.
After that, you can create a post build step to copy the file to the deployment folder (or a subfolder) so that even in your debug environment the file will be in the correct place. The property "Copy to Output Folder" on the data file will do this as well if you just need the file to be in the output path for a project.
If you need more control, n the post build steps you can use macros like $(ProjectPath) to reference where the project files are located and $(TargetDir) to reference where the output directory will be.

Categories