ReadAllLines() local directory not working - c#

For some reason the ReadAllLines() looks in the wrong folder.
string[] LoadLines = File.ReadAllLines(#"Assets\\UserFile.txt");
The "Assets\UserFile.txt" is located where the exe file is.
The Debugger throws a System.IO.DirectoryNotFoundException with a comment:
"Could not find a part of the path C:\WINDOWS\SysWOW64\Assets\UserFile.txt"
Why is it checking in the wrong folder?

Try this...
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"Assets\UserFile.txt");
string[] lines= File.ReadAllLines(path);
Note: This will look in the folder you are executing from so make sure the folder/file exists in there.
If the executing folder is your bin folder, ensure that the file property is set to "Content" and "Always copy" or "Copy when newer" within Visual Studio.

Relative path names are resolved relative to the working directory of the process, not relative to the executable. So presumably your process has a working directory of c:\Windows\SysWOW64.
If your code needs to load assets that are effectively bundled with the application, I'd use embedded resources as a way of not having to worry about physical file paths.

Related

C# File Disappeared after FileInfo.MoveTo with Local Path (Windows)

I Ran FileInfo.MoveTo("filename.txt") with just a name instead of passing a full path and the file just disappeared. I believe in linux this would make it go to the root directory "/", but on Windows I'm not sure if there is a such thing as a root directory beyond just C: Is there any way to locate my lost file?
It is likely in the working folder that your executable is running from. For example, MyApp\bin\Debug, depending on the configuration you are running in.
It should be in project folder. Usually files without specefying path are saved there. (in folder with .exe file)

C# how to read a file from a folder under the project root directory

When a form loads, I need to read a binary file under the /skubin folder and use it to populate a List. But I’m unable to open the file. When I do, I receive an error indicating that the file doesn’t exist.
Below is the snippet of my code which I am trying to read the file from the folder.
string startpath = Application.StartupPath;
string BinDir = Path.Combine(startpath, "skubin");
binNanme = Path.Combine(BinDir, "skuen.bin");
if (!File.Exists(binNanme))
{
MessageBox.Show("Load bin fail");
return;
}
When checking the BinDir value, instead of pointing to <project_root>/skubin, it's pointing to <project_root>/bin/Debug/skubin.
I am not understanding why it is pointing to /bin/Debug folder.
Right-click on the .bin files in the skubin folder within solution explorer and select properties. Set "Copy to Output Directory" to "Copy Always". This should solve your problem without making any code changes. I am assuming you need those binary files at run-time.
When you compile your project, the results are placed into a {projectFolder}\bin\Debug, and when debugging, the application is run from there.
You have 2 choices:
Keep your code as-is, and in the properties window, mark your bin files as "Copy if newer" or "Copy always". This will copy the files into \bin\Debug\skubin when you compile, and access them from there. This would simulate deploying those files with your application.
-- Or --
Modify your code to move up 2 directories from Application.StartupPath:
string BinDir = Path.Combine(startpath, "..\\..\\skubin");
This would be the option if you're not thinking about deploying your application, and just running it from within your project folder.
string filepath = Server.MapPath("~/skubin")
filepath= Path.Combine(filepath, "skuen.bin")
// open the file
//if not in a controller, you may use this
HttpContext.Current.Server.MapPath("~/skubin")
For Windows App, you may try Best way to get application folder path

Finding a specific file path when two files have the same name in different locations in C#

I'm trying to load and save an xml file called Modules.xml in my code. I have currently got the file path hardcoded as shown below. I am trying to get the file path within my code without it being hardcoded.
I have tried using Path.GetDirectoryName and new FileInfo("Modules.xml").Directory.FullName. However, both of these target the file in my debug folder, when the file I need is in the main solution folder.
Is there a way to target the file in my main solution folder instead of my debug folder? (both files are called Modules.xml)
doc.Save("C:\\Users\\Matthew\\Desktop\\Year4\\Object Oriented\\Project1\\Project1\\Modules.xml");
Both file locations are shown below:
C:\Users\Matthew\Desktop\Year4\Object Oriented\Project1\Project1\Modules.xml
^^^this is the file path I need for my code^^^
C:\Users\Matthew\Desktop\Year4\Object Oriented\Project1\Project1\bin\Debug\Modules.xml
The best approach here would be to use a configuration file, e.g. app.config, for storing such a string. Then you can change file path without recompiling the code, and your file can be stored in any location accessible by application.
If you really want to access your file the way you explained, AppDomain.CurrentDomain.BaseDirectory will provide you with the bin/Debug location in runtime. Then you can find a relative path from there like:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\..\", fileName);
where fileName is "Modules.xml" for example.
I have tried using Path.GetDirectoryName and new
FileInfo("Modules.xml").Directory.FullName. However, both of these
target the file in my debug folder, when the file I need is in the
main solution folder.
That's because bin\Debug is your working directory when you start and run the project. To change that, you can set the working directory environment variable to point to your solution directory (instead of bin\debug|release) which I wouldn't recommend that. Because when you finally endup with development, and release the application, there wouldn't be any solution directory that holds your XML file. What I can suggest is to copy your XML file to the output folder. Either you are in development (debug) or production (release) mode, the XML always going to be copied to final directory. And you can access the working directory with something like AppDomain.CurrentDomain.BaseDirectory. To enabling copy XML to output directory, right-click on it, choose Properties, set Build Action to None, and set Copy to Output Directory to Copy Always or Copy if newer. You're good to go now.

Why does my file directory include '/bin'?

I'm trying to find a file in a settings folder in my application. I have a xml file there. When I run the following code:
XDocument xDoc = XDocument.Load(#"..\settings\Settings.xml");
I get the DirectoryNotFoundException and the exception says not found at \bin\settings\Settings.xml'., instead of above. I even tried the full root directory to see the issue, C://... but it still includes a bin folder?
How can I have it so it doesn't include the bin part?
By default, the build results in Visual Studio are saved in a folder like bin\Debug. Since you use a relative path that jumps one folder higher, you get yourProjectFolder\bin\settings\Settings.xml. That file doesn't exist, since it's presumably in the project folder, not the bin folder.
The typical way to deal with this is to make sure the files that are supposed to be a part of the content actually have Build Action set to Content.
Using a rooted path definitely works - most likely, you made a mistake somewhere; either the path isn't rooted at all, or you're doing something like interpreting the path as an URI rather than a file path. XDocument.Load takes a URI, not a file path - the proper way to reference an absolute path on the filesystem would be file://C:/ThePath/Settings/Settings.xml.

Environment PATH variable affecting Relative File Path(s)

I had this console application. Now i have added Environment variable PATH to its setup so that it can be executed from any location through Console. Strangely, the same application is breaking after this change.
Installation directory contains, BIN and CONFIG folder. Exe is placed inside BIN folder.
I have this line of code,
WriteToFile(#"..\Config\Settings.xml")
The path used to write to a file Settings.xml inside Config folder inside the INSTALLATION DIRECTORY. However, now it tries to write to settings.xml inside Config folder at EXECUTION PATH.
So, if i execute my app from console as c:/users/guest/app.exe, it would try to interpret path relative to this location AND NOT relative to installation directory for the application.
Any help, suggestions?
Get the path of the executing assembly then add to it the folder and file name:
string pathOfExecutingAssembly = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string settingsPath = pathOfExecutingAssembly + "\\..\\Config\\Settings.xml"
Why don't you try getting the Executing Application's Path and append it before the path where you want to save
Path starting from \ means: start from the root directory on the current drive. \Config\Settings.xml executed from any C subdirectory gives: C:\Config\Settings.xml.
BTW, do you post exact code? It should be WriteToFile(#"\Config\Settings.xml") or WriteToFile("\Config\Settings.xml")
In any case, you need to decide, whether you want to search configuration file using absolute path, or path relative to current directory/installation directory/executable directory. The code, installation package and execution command should be changed accordingly.

Categories

Resources