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
Related
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
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");
I am trying to create a Bitmap using:
bitmap = new Bitmap(#"Movies\View\Images\missing_person.bmp");
However, I am receiving a System.ArgumentException error.
The file I'm calling the above code from is located in:
MyProj\DisplaySideBarCommand.cs
The images are in:
MyProj\Movies\View\Images\missing_person.bmp
I also tried using:
bitmap = new Bitmap(#"..\Movies\View\Images\missing_person.bmp");
but received the same error.
It is going to look for the files relative to the executing assembly. When you build your project it is probably output to a directory like bin\debug or bin\release. You could build your relative path to backtrack from there, or you could copy the files to the output directory.
If you set the build action to Content on the files, they will be copied to the output directory (including sub folders) on build and then you should be able to build the correct relative path from there.
If you are using the default settings, the debug binaries would be in ProjectDirectory\bin\Debug\ - therefore, you might want to try #"..\..\Movies\View\Images\missing_person.bmp"
This is because the images are located in your project folder, not your output folder.
string projectFolder = "..\\..\\"; // Goes back to the project folder
Once you got the projec path simply use it like this:
bitmap = new Bitmap(projectFolder + #"Movies\View\Images\missing_person.bmp");
I would suggest you to move your files to the output folder rather than storing them in your project. Since normally you only distribute the output folder and not your whole project (Unless it's open source of course.)
I have some text files to be read that are located in the visual studio project. My app.config file should adapt the path of these files automatically. i.e., suppose I have a file in the location C:\Visual Studio\Test Project\Read.txt, the same project when I put into D:\ drive, I should not change the path to D:\Test Project\Read.txt It should adapt the change in location automatically.
Your app.config file cannot adapt automatically. Generally, this is the task of installation or deployment scripts, to make sure that all the configuration is set up properly.
However, your program can dynamically adapt if it knows that your configuration files is storing relative paths. Instead of doing
var reader = new StreamReader(Configuration.AppSettings["fileToRead"]);
Do this (reference the file relative to the currently executing assembly):
var path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
path = Path.Combine(path, Configuration.AppSettings["fileToRead"])
var reader = new StreamReader(path);
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.