How to move two folder back - c#

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

Related

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

C# get relative path of resources folder

I want to acess a .txt file, which I stored in the resources folder of my project, there where all the imported pictures are stored as well.
I want to use something like a relative path, since every user would have safed his programm somewehere else on his Pc, but there is always the resources folder at the same place, compared to the programm folder.
I tried to used this: displayText = System.IO.File.ReadAllText("Resources\\startmessages.txt"); but this isn't working.
I get this error message: System.IO.DirectoryNotFoundException:, it lists the unrelative path to the .txt there as well, so I don't get, why it cant read it.
Thanks for your Help.
What #ChetanRanpariya is trying to tell you is, that your programm is built in another folder than your folder Resources is sitting to. So you have explictly tell your file Resources\startmessages.txt to copy itself on build process, so it get copied to said another folder. Assuming that you are using Visual Studio, you have to right click on your file and set Copy To Output Directory to true. Its relative folder path (Resources\) will be taken over. You find your build folder somewhere in your bin folder depending on configuration and framework. :)
Current Path where your executable is
Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).FullName
Path to Solution
If you are using Visual Studio and need to access the folders in the solution directory, you can use .Parent method,
Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName
Use of Path.Combine
and once you have the location of your Resource folder, use Path.Combine to get the location to read files / content etc
Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Resources\\startMessages.txt")

Access a file in the referencing dll

I have a c# class library project with name ExampleLibrary1 in which I have to access a text file in project folder. I tried all the below ways for get directory path.
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyFolder1 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyFolder2 = Assembly.GetExecutingAssembly().CodeBase;
string assemblyFolder3 = Directory.GetCurrentDirectory();
I am referencing the dll in consoleapplication1 and invoking the code which accesses the text file. All the above methods give me the below output and unable to access the file.
C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
file:///C:/Users/Desktop/ConsoleApplication1/ConsoleApplication1/bin/x64/Debug/ExampleLibrary1.DLL
C:\Users\shrallap\Desktop\ConsoleApplication1\ConsoleApplication1\bin\x64\Debug
My requirement is I have to read a file in ExampleLibrary1 code, script is also in ExampleLibrary1. But the code invocation happens from ConsoleApplication1
If I don't misunderstand your question, your have a text file, let's call it "yourtextfile.bat" in the project folder of ExampleLibrary1, in the same folder where the file ExampleLibrary1.csproj is.
You cannot access it from your code. Project folder is where you organise your source code on the dev machine, on users' environment, there is no project folder.
Of course, you can use relative path like this to access it
..\\..\\..\\..\\ExampleLibrary1\\yourtextfile.bat
But it only works in debugging.
You have to copy the text file to the output folder at build, then it will be the same folder as the dll/exe, and you can access it without worrying about its actual path, just use relative path "yourtextfile.bat" to access it.
In .NET, relative path is relative to the Environment.CurrentDirectory at runtime, usually the folder where exe resides if you double click to launch the exe. It is NOT relative to the project folder.

Deploying c# application issues

I have a application with one folder which i added by right clicking the project, selecting add folder. Inside this folder i have xml files which are set to build action:content, copy to output directory: copy if newer (i have tried setting to embedded resource) As well as this i have a few text files and so on.
In my bin/debug output directory i have the exe, the folder with the xml, the stand alone .txt files and so on. My problem is, if i send the exe to my friend to try he always gets an exception thrown.
Say he puts the exe on the desktop, my programme at some point reads the filenames of the xml files in the folder. It uses the following code to do so
String[] filePaths = Directory.GetFiles(#"DataSources\");
I assume that because of this, when the exe runs from the desktop, it expect the folder of .xml files to be in the same place? I have the same type of exception when trying to read the .txt files too. What am i doing wrong here?
Thanks for your time
When reading from files using relative paths you get the one relative to the applications current directory. tip: In C# you can see what directory that is using Environment.CurrentDirectory.
So if you create a shortcut on your desktop, you need to make sure you right click the shortcut and set its "Start in"-folder to the directory of your application. That way its current directory will be set when its started and relative paths will be relative to that path and not the path of the shortcut.
If you actually moved the exe file to the desktop you also need to move any resources that it needs, so if it wants a folder named "datasources" you would have to move that folder as well, or set the current directory when you start the application.
Have you tried something like: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.executablepath.aspx or http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx ?
So
Directory.GetFiles(environment.currentdirectory + #"\DataSources\");

Hard Coded Paths in a .NET Program

I am developing an application in C#. I have a folder called myfolder it contains a file called mypoints.bmp. The folder myfolder is in my project folder it is in D drive. The path is D:\Myproject\myfolder\mypoints.bmp.
Now, in my program, whereever I need mypoints.bmp I have hardcoded the whole path. When my project is copied in to a different system under C drive, I am not able to run my project because of the hardcoded path. How can I give the path so that there will not be any problem even if it is loaded in to a different system under a different drive.
The best would be to store the path in a configuration file.
Add -> New Item -> Application Configuration File
Then you can use the following class to pull the value you're looking for:
System.Configuration.ConfigurationManager
Have a look here on the usage.
If the images you are referring to are non-changing and are simply acting as a resource for your application then you could consider embedding them in resource files which are compiled as part of your assembly. That way you need never worry about paths or copying them.
If the BMP file is used in the code and is accessed in runtime, there is no point in keeping it just in the project directory. it should be also present in the outputdirectory.
i.e you could write a post-build command to copy your folder to the output directory.
like copy "$(ProjectDir)\MyFolder\*.*" "$(OutDir)"
then in the code you could just write the relative path i.e "MyFolder\MyPoints.bmp"
But please remember one thing. If this BMP file is not going to change through out your program execution, it is better that you put it as a resource.
You can use something like GetCurrentPath(), which will return your .exe file path, then add to this path your \myfolder\mypoints.bmp. This will not be depend on C or D or ... drive and folder
There is one path that you can always reliably find, no matter how your program got deployed to the target machine: the directory in which your .exe is stored.
Take advantage of this, put the .bmp file in the same directory. Or a subdirectory of the install directory. You didn't say what kind of program you wrote, it is easy with Application.ExecutablePath in Windows Forms. But the generic solution that works everywhere:
public static string GetImagePath(string filename) {
string exeFile = System.Reflection.Assembly.GetEntryAssembly().Location;
string exePath = System.IO.Path.GetDirectoryName(exeFile);
string imgPath = System.IO.Path.Combine(exePath, #"images");
string imgFile = System.IO.Path.Combine(imgPath, filename);
return imgFile;
}
Which assumes the images are stored in a subdirectory named "images". Tweak as necessary.
Last but not least: don't forget that you can add images to your program's resources so it is baked in the .exe file. Project + Properties, Resources tab. Highly recommended.
You can also use predefined or existed system variable. Anyway you must decide when the user (or you) have to define that path (in config file or wherever) - during instalaltion, first run, before first run or in any time when app is running.
Personally I would use the Environment class in C#. Then I will locate the local app settings folder using the Environment.SpecialFolder enum.
I will then store all my applications specific files inside a folder in the local app settings folder.
This way you are also UAC safe, since UAC will complain if you want to store files in Program Files if you are not Administrator.

Categories