C# Loading a xml file from the current directory? - c#

I use the line below in my C# winform app, this works great but occasionally if the program is being run from the command line I get an error that the config.xml file cannot be found. This is because the 'working directory' is different (I think), I need to say "load config.xml from current directory", how would I do this?
docXML.Load("config.xml");
Thanks
Jonathan

string fileName = Path.Combine(Application.StartupPath, "config.xml");

string Path = "";
string Filename = ConfigurationManager.AppSettings("Filename");
for loading from current directory
Path = System.Web.HttpContext.Current.Server.MapPath(Filename);
for loading from Base directory
Path = AppDomain.CurrentDomain.BaseDirectory + Filename;

Related

Get the filepath of a static file to work local and on server

I want to provide a new file needed for configuring my application - here it's the settings.json:
How do I get the correct path of the file?
I tried:
System.Reflection.Assembly.GetExecutingAssembly().Location // gets a DLL somewhere /Temporary ASP.NET Files/
but when I publish it to a customers server the location is next to the web.config like this (and is a different path):
Any idea?
You can use AppDomain.CurrentDomain.BaseDirectory to get base directory of your application.
Something like this should work:
string settingsJson = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json");
You can try one of these two methods:
string path = System.IO.Directory.GetCurrentDirectory();
string path = Environment.CurrentDirectory;
Path.Combine(path, "settings.json");

Error the relative path of resources folder auto change to absolute path in C#

The code below i use to read lines from file test.txt in my folder Resources of my project.
string[] test = File.ReadAllLines(#"Resources\test.txt");
The properties are already change to "Content" and "Copy Always".
When i run the program, somtimes the path auto change to the Absolute path as:
"C:\Users\Documents\Resources\test.txt
And the program error because cannot find the path.
You are using a relative path to the file, which relies on the CurrentDirectory being valid. This is either changing, or not being set to the desired directory when the program is executed. You can test this failure with this code:
string CurrentDirectory = Environment.CurrentDirectory;
Log.Trace($"CurrentDirectory = {CurrentDirectory}");
System.IO.File.ReadAllText(#"Resources\test.txt");
Environment.CurrentDirectory = #"C:\Tools";
// changing the current directory will now cause the next command to fail
System.IO.File.ReadAllText(#"Resources\test.txt");
You should not rely on the CurrentDirectory path being set correctly. Get the directory of the current running executable with something like this:
string ExePath = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location)
.Directory.FullName;
string FullPath = System.IO.Path.Combine(ExePath, "Resources", "test.txt");
System.IO.File.ReadAllText(FullPath);
Yo could use
Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "Resources", "test.txt"
to get the path.
But to your problem: I think, the problem is the ReadAllLines, because it wants to convert the string to an absolute path. So the problem shouldn't exist anymore, if you localize the string, or even make somenthing like:
var path = "" + "Resources\\test.txt";
var test = File.ReadAllLines(path);
I couldn't test this though because I couldn't reproduce your problem.

Get path without file name save dialog

I would like to extract the selected path from Save dialog, excluding the file name.
The following code retrieves the full path + the file name with its extension.
placeToSaveDocument = Path.GetFullPath(saveFileDialog.FileName);
Please do not suggest to use Folder Browser Dialog instead, because I have a reason why not to use it.
Any ideas?
You're probably looking for Path.GetDirectoryName(saveFileDialog.FileName).
Example:
string filePath = #"C:\MyDir\MySubDir\myfile.ext";
string directoryPath = Path.GetDirectoryName(filePath);
//directoryPath = "C:\MyDir\MySubDir"

Get File Path of A File In Your Current Project

How do I programmically get the File Path of a File In my project?
string fileContent = File.ReadAllText(LocalConstants.EMAIL_PATH);
The EMAIL_PATH I added to my project as a text file. This line of code throws an exception because by default it is looking in the system32 folder for some reason. I need to set it to the projects directory.
You could use Path.Combine and AppDomain.CurrentDomain.BaseDirectory:
string fileName = "SampleFile.txt";
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LocalConstants.EMAIL_PATH, fileName);
Returns in a test project in debug mode this path(when LocalConstants.EMAIL_PATH="Emails"):
C:\****\****\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsFormsApplication1\bin\Debug\Emails\SampleFile.txt
You can use Environment.CurrentDirectory
See: http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx
For further reading.
edit*
string temp = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Will do the same and is perhaps a little safer.
This worked for me System.AppDomain.CurrentDomain.BaseDirectory.ToString()

Open a text file with WPF

There is a text file that I have created in my project root folder. Now, I am trying to use Process.Start() method to externally launch that text file.
The problem I have got here is that the file path is incorrect and Process.Start() can't find this text file. My code is as follows:
Process.Start("Textfile.txt");
So how should I correctly reference to that text file? Can I use the relative path instead of the absolute path? Thanks.
Edit:
If I change above code to this, would it work?
string path = Assembly.GetExecutingAssembly().Location;
Process.Start(path + "/ReadMe.txt");
Windows needs to know where to find the file, so you need somehow specify that:
Either using absolute path:
Process.Start("C:\\1.txt");
Or set current directory:
Environment.CurrentDirectory = "C:\\";
Process.Start("1.txt");
Normally CurrentDirectory is set to the location of the executable.
[Edit]
If the file is in the same directory where executable is you can use the code like this:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "1.txt");
Process.Start(file);
The way you are doing this is fine. This will find the text file that is in the same directory as your exe and it will open it with the default application (probably notepad.exe). Here are more examples of how to do this:
http://www.dotnetperls.com/process-start
However, if you want to put a path in, you have to use the full path. You can build the full path while only caring about the relative path using the method listed in this post:
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/e763ae8c-1284-43fe-9e55-4b36f8780f1c
It would look something like this:
string pathPrefix;
if(System.Diagnostics.Debugger.IsAttached())
{
pathPrefix = System.IO.Path.GetFullPath(Application.StartupPath + "\..\..\resources\");
}
else
{
pathPrefix = Application.StartupPath + "\resources\";
}
Process.Start(pathPrefix + "Textfile.txt");
This is for opening a file in a folder you add to your project called resources. If you want it in your project root, just drop off the resources folder in the above two strings and you will be good to go.
You'll need to know the current directory if you want to use a relative path.
System.Envrionment.CurrentDirectory
You could append that to your path with Path
System.IO.Path.Combine(System.Envrionment.CurrentDirectory, "Textfile.txt")
Try using Application.StartupPath path as default path may point to current directory.
This scenario has been explained on following links..
Environment.CurrentDirectory in C#.NET
http://start-coding.blogspot.com/2008/12/applicationstartuppath.html
On a windows box:
Start notepad with the file's location immediately following it. WIN
process.start("notepad C:\Full\Directory\To\File\FileName.txt");

Categories