streamreader paths to file - c#

While in a search to learn more about the streamreader, i came across this from
StreamReader path changes automatically
post #2 by
Hans Passant
var exedir = Path.GetDirectory(Assembly.GetEntryAssembly().Location);
var path = Path.Combine(exedir, #"Config\launcher.txt"); using (var
reader = new StreamReader(path)) {
//... }
Now I understand the "never hard code the file" part, In delphi, I am able to specify a custom file path based on the files in a directory ie.
Read all file names in a directory, user chooses a file name, and then I read the contents of the file
Delphi, I just used a string and added the file name to the end, how does that differ from the code above, and is there a different method to this above?
and btw. Could someone just explain in a bit more detail, the methods and variables used and why (i am still new to c#)

I think what Hans is saying here is that if you are expecting the files to be relative to your application code, then expliclty look relative to your application code. Don't rely on the current directory being the base location of your application, as that is not guaranteed (and can change during your application's execution). So what the code does is:
obtain the entry-point assembly (the assembly with the Main method that was executed at startup), and obtion the file location of that assembly: Assembly.GetEntryAssembly().Location
obtain the directory from this file path: var exedir = Path.GetDirectory(...);
construct a path relative to this directory: var path = Path.Combine(exedir, #"Config\launcher.txt");
create a reader based on the final path: using (var
reader = new StreamReader(path)) ...

GetEntryAssembly returns, according to the documentation:
The assembly that is the process executable in the default
application domain, or the first executable that was
executed by AppDomain.ExecuteAssembly.
And the Location property returns the full path of the assembly. So
Assembly.GetEntryAssembly().Location
is the full path of the executable. In Delphi you would write ParamStr(0) or Application.ExeFileName.
Path.GetDirectory strips off the file name and leaves the directory. In Delphi you'd use ExtractFilePath.
And Path.Combine simple joins two path components, adding a path separator if necessary. In Delphi you'd use TPath.Combine from the IOUtils unit.
So the code in the question constructs the full path to a file named
<exedir>\Config\launcher.txt
where is the directory containing the main executable assembly which is of course known only at runtime.
There's really nothing particularly different between the way things are done in Delphi and C#. To construct the same path in either language you take the exact same steps modulo syntax/method name differences.
Possibly you are in the habit of assuming that the working directory is the directory containing the executable assembly. If so, lose that habit. The working directory is meaningful for a console application and for such an application it can be considered an input to the program. But don't expect it to be stable in a GUI program. And never assume that the working directory contains the executable. That assumption is not valid.
On the other hand, perhaps you really do want a path relative to the working directory. In which case simply supply the filename and let the system take care of the rest.

Related

Get a file path C#

I have a .txt file that I need to read in my program. For the moment I have the directory hardcoded as such:
file = new StreamReader(#"C:\Users\<username>\Documents\File.txt");
However that will (obviously) not work on any other PC that does not have that access to altering the code, or (by some strange happenstance) the same directory as the original code.
How can I get the full file path to set it in my program using C#?
You could create the file in their Application Data directory (they could still find it if they wanted to, but at least it wouldn't be as obvious as the My Documents folder).
When you want to access it, use the Environment class. There are methods for locating special folders for the current user, without resorting to hard-coded paths:
var filePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "File.txt");
Option 1:
Application.StartupPath can be used for the purpose.
It gets the path for the executable file that started the application, not including the executable name.
Keep File.txt with your executable.
Option 2:
Use Environment.SpecialFolder.ApplicationData
It gives directory that serves as a common repository for application-specific data for the current roaming user.
NOTE: If you want to restrict the user to look into the contents of File.txt then you might need to encrypt the contents.

C# File Handling: Create file in directory where executable exists

I am creating a standalone application that will be distributed to many users. Now each may place the executable in different places on their machines.
I wish to create a new file in the directory from where the executable was executed. So, if the user has his executable in :
C:\exefile\
The file is created there, however if the user stores the executable in:
C:\Users\%Username%\files\
the new file should be created there.
I do not wish to hard code the path in my application, but identify where the executable exists and create the file in that folder. How can I achieve this?
Never create a file into the directory where executable stays. Especially with the latest OSes available on the market, you can easily jump into the security issues, on file creation.
In order to gurantee the file creation process, so your data persistancy too, use this code:
var systemPath = System.Environment.
GetFolderPath(
Environment.SpecialFolder.CommonApplicationData
);
var complete = Path.Combine(systemPath , "files");
This will generate a path like C:\Documents and Settings\%USER NAME%\Application Data\files folder, where you guaranteed to have a permission to write.
Just use File.Create:
File.Create("fileName");
This will create file inside your executable program without specifying the full path.
Don't forget to add:
using System.IO;
You can get the full path to your new file with:
string path = Path.GetDirectoryName(Application.ExecutablePath) + "\\mynewfile.txt"
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
MessageBox.Show( path );
http://msdn.microsoft.com/en-us/library/aa457089.aspx
In modern operating systems, the accepted answer of:
var systemPath = System.Environment.GetFolderPath(
Environment.SpecialFolder.CommonApplicationData
);
var complete = Path.Combine(systemPath , "files");
will produce a user agnostic path like: "C:\ProgramData\files"
To produce a user-based path similar to: "C:\Documents and Settings\%USER NAME%\Application Data\files"
You should use SpecialFolder.ApplicationData or SpecialFolder.LocalApplicationData instead.
I like to give the user the choice. I would default the directory to something like Environment.SpecialFolder.CommonApplicationData and let them read and edit the path at will. If in a console app display the path in help and allow them to pass it via command line argument.
This saves them the hassle of hunting for the folder. If they point to a path you cannot write to then you throw the error and let them decide what to do.

Using WritePrivateProfileString to write path issue

I am using WritePrivateProfileString in c# (through DllImport) to store paths taken from textboxes on the interface. And the .ini file name is hardcoded in my application
string ini_file = ".\\config.ini";
However, when the file writing happens, the configuration file is written to the first path taken from the interface instead of writing it to the exe directory. Which is quite odd.
Debugging shows that the values are sent correctly to the WritePrivateProfileString but it still is written to the wrong location. Anyone knows why is that happenening?
I'd guess that something is changing the working directory of your process, most likely your code in the process. Note that the documentation has this to say:
If the lpFileName parameter does not contain a full path and file name for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.
Now my guess is that this applies if you supply just a file name. Because your file name starts with . I believe that will force the function to start from the current working directory.
Having said all of that, and no matter what the cause of the problem is, you should use a fully-qualified path in order to make sure the file is written where you want it to be written. Whenever you want the file to go in a specific directory, it's always easiest to force that by using fully-qualified paths.
You can find the path to your executable using Application.ExecutablePath and then remove the file name part.
Another point to make is that the same directory as the executable may be a bad choice. If your program is installed under the Program Files directory then the directory which contains the executable will not be generally writeable. I think you should consider using a directory under in the user profile. Look for one of the Environment.SpecialFolder values.
Further to David Heffernan's answer - you can use
Path.GetDirectoryName(Application.ExecutablePath);
to safely get just the running application's folder part.
If you're in a dll rather than an executable, you can use
Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
Both require System.IO, and were originally posted here. Second example also requires System.Reflection).
Application data files are supposed to be written to the LocalApplicationData special folder.
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
You typically will not have permissions to write into the Program Files folder etc.

Relative path to a file using C#

I have a command-line program that takes a configuration file as a parameter, that is, C:\myprogram.exe -c C:\configFiles\MyConfigFile.txt. I want to be able to make it so that I do not have to type the absolute path to the configuration file, so instead of the above I can just enter C:\myprogram.exe -c MyConfigFile.txt
I'm not familiar enough with how C# deals with paths to understand if or how this can be done. Any insight is appreciated.
Use Path.GetFullPath()
Something like:
string path = "MyConfigFile.txt";
string fullPath = System.IO.Path.GetFullPath(path);
That's if the config file is in the current directory. If they're stored in a standard folder you can use Path.Combine()
string basePath = "C:\Configs";
string file = "MyConfigFile.txt";
string fullPath = System.IO.Path.Combine(basePath, file);
You are only passing in a string. It is up to you to handle it in a relative path way.
If you used this code, it would by default support relative paths.
FileInfo will attempt to use the path in Environment.CurrentDirectory first, if the path provided is not explicit.
var file = new FileInfo(args[1]); // args[1] can be a filename of a local file
Console.WriteLine(file.FullName); // Would show the full path to the file
You have some general options:
Store the directory path in the config file (you said you don't want to do this)
Have the user enter a relative path (....\MyFile.txt)
Programmatically search for files matching the name (very slow and prone to locating multiple files of the same name)
Assume the data file is in the executing directory
Any way you slice it, the user must indicate the path to the directory, be it in the config file, entering relative path, or selecting from a list of files with identical names found in different directories.
ANALOGY: You place a textbook in a locker, somewhere in a school. You ask your friend to get the book from "a locker", without hinting as to exactly which locker that may be. You should expect to wait a very long time and end up with 50 similar books. Or, provide a clue as to the hallway, bank of lockers, and/or locker number in which the book may be stored. The vagueness of your clue is directly correlated with the response time and potential for returning multiple possibilities.
Without the relative path as part of the input argument, your application would need to:
either search for the file that is passed in
append the path name of the Config directory to the filename
Well, standard .NET classes are working with relative paths in same way as with absolute, so, you could use them without any problems. If C: root is working directory of your program, you could use c:\myprogram.exe -c configFiles\MyConfigFile.txt and it will point to c:\configFiles\MyConfigFile.txt.

File Not Found Exception thrown for XML file possibly caused by Outlook

I'm getting a file not found exception when my application is called by Outlook. It's called when an email is saved to the computer the app is called and performs an action on the saved message.
My app uses a XML file to store configurable settings but this file can't be found when Outlook calls to executes the application. If I run the program manually then it works fine.
The interesting thing about the exception is this:
System.IO.FileNotFoundException: Could not find file 'C:\Program Files\Common Files\System\MSMAPI\1033\settingsOpened.xml'.
Why does Outlook think that the file is here ? This isn't the path for the file but I'm sure is related to Outlook. The way I'm referencing the path in the code is just:
XmlDocument xDoc = new XmlDocument();
xDoc.Load("settingsOpened.xml");
With the file being in the same folder as the .exe. I don't want to hard code the full path in for the XML files either.
Any help would be greatly appreciated.
Thanks,
Ross
From the code shown I would assume that it takes the current path as the location to look for the file. The current path is a bit unpredictable as certain operations effect its value and the value is persisted on each call. I.e. when another part of your application, or even another applciation, sets the current path this value is used the next time around. To set the current path it is enought to use a common dialog to browse for a certain file.
In your case I'd try to either to
specify the path explicitly by deriving it from one of the well known folders (e.g. the user's app path - look for Environment.GetFolderPath and Environment.SpecialFolder)
or
to resolve the path relative to your Dll's assembly path.
To find the assembly path for myType you can use the following code:
String strPath = System.IO.Path.GetDirectoryName(typeof(myType).Assembly.CodeBase);
In either case you should consider that in newer windows operating systems the user does not have write access to all paths of the system drive.

Categories