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?
Related
the problem that i have with my application is about how to reference some files, when i load and image, etc, i use Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")); and this works fine for debugging and for some files, but doesn't work for some essential files, credentials.txt, config.ini, this files are searched in appdata when i run the published file and i don't know how i should reference them.
I try to generate some initial files so i am sure where they are and that they exists, but for folders that works great with
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
with that i can make the folders where the app is run but you can't generate a file without load the content of the original file, and i don't know how to reference them.
Example:
Project.
Root of the project.
utils/key/credentials.txt
When the published file is executed i want to generate and store credentials.txt like this:
Executable (app.exe stored for example in "my documents")
"my documents"/utils/key/credentials.txt
how i do that? when i run the published application you just have the .exe, the dlls, and the resources are embebbed, so the uri doesn't works.
Assuming you have sufficient permissions, you could create a folder in the output folder of your compiled .exe at runtime using the Directory.CreateDirectory method.
If the utils/key/credentials.txt file is part of your deployment, you should set its Build Action to Content and the Copy to Output Directory property to Copy if newer in Visual Studio. This will add the utils and key folders to the output directory of the .exe, which is typically c:<project-folder\bin\Debug or \Release when you build from Visual Studio.
You can get the absolute path of the output directory like this:
string path = System.IO.Path.GetDirectoryName(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
Depending on your requirements, you may then append the relative path of the file within your app to the absolute path.
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
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
Currently I write data using StorageFolder storageFolder = ApplicationData.Current.LocalFolder
This works well on my computer however the result is that data gets written in an obnoxious file path: C:\Users\User1\AppData\Local\Packages\fd93e2b2-6652-4264-be36-c5e45d17d2b4_ywwvhtjmx9rt8\LocalState
However I want to send the UWP application to someone else so that they can test it and I would like to be able to save the files all in one folder (the same folder as the solution) so that they can just unzip it and run it without having to save the files in a random location like above.
Is it possible to do this in UWP?
You can get the install location of the application from the Package class.
// Get the path to the app's "data" folder.
string rootDirectory = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path = rootDirectory + #"\Data";
Then you can get the Storage folder from the path
// Get the folder object that corresponds to this absolute path in the file system.
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
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");