C# - Determine file path - c#

I am using the following code to load a custom cursor for my program:
public static Cursor LoadCustomCursor(string path)
{
IntPtr hCurs = LoadCursorFromFile(path);
if (hCurs == IntPtr.Zero) throw new Win32Exception(-2147467259, "Key game file missing. Please try re-installing the game to fix this error.");
Cursor curs = new Cursor(hCurs);
// Note: force the cursor to own the handle so it gets released properly.
FieldInfo fi = typeof(Cursor).GetField("ownHandle", BindingFlags.NonPublic | BindingFlags.Instance);
fi.SetValue(curs, true);
return curs;
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr LoadCursorFromFile(string path);
And then:
Cursor gameCursor = NativeMethods.LoadCustomCursor(#"C:/Users/User/Documents/Visual Studio 2015/Projects/myProj/myProj/Content/Graphics/Cursors/cursor_0.xnb");
Form gameForm = (Form)Control.FromHandle(Window.Handle);
I am wondering if this absolute path above will also work if the project folder is for example moved to D:/ partition or another folder on C:/? Can I do something like this:
string myStr = Assembly.GetExecutingAssembly().Location;
string output = myStr.Replace("bin\\Windows\\Debug\\myProj.exe", "Content\\Graphics\\Cursors\\cursor_0.xnb");
And use output for the path of the cursor file? Is Assembly.GetExecutingAssembly().Location dynamic (changes every time the program folder is moved)? Or is it always the same as when the project was built?

You can use Environment.CurrentDirectory. Example:
string cursorPath = #"Content\Graphics\Cursors\cursor_0.xnb";
string output = Path.Combine(Environment.CurrentDirectory, cursorPath);
Environment.CurrentDirectory returns the full path of the current working directory and you can use # to escape the literal \ all at once if you place it in front of the string.

This approach is not the best way.
Better to use relative paths, not absolute.
You can use ".." to move one folder up from your current location.
For example
var output = #"..\..\..\Content\Graphics\Cursors\cursor_0.xnb";
Is equals to
string myStr = System.Reflection.Assembly.GetExecutingAssembly().Location;
string output = myStr.Replace("bin\\Windows\\Debug\\myProj.exe", "Content\\Graphics\\Cursors\\cursor_0.xnb");

Your absolute path will only keep working if your cursor file lives at the exact path specified: #"C:/Users/User/Documents/Visual Studio 2015/Projects/myProj/myProj/Content/Graphics/Cursors/cursor_0.xnb". Relating the cursor file's location to your .EXE file is a better idea, but you'll need to maintain the relative folder structure you specify in code. Your code now depends on the .EXE living in directory <appRoot>\bin\Windows\Debug, which you probably won't want when deploying your application. (Instead you'll probably put the .EXE in the application's root folder, with resource files going into subdirectories.) For such a structure, you could write (code was never compiled and may therefore contain typos or other errors):
var exe = Assembly.GetExecutingAssembly().Location;
var exeFolder = System.IO.Path.GetDirectoryName(exe);
var cursorFile = System.IO.Path.Combine(exeFolder, "relative/path/to/your.cur";
(For added benefit, this code will keep working when the .EXE file is renamed.)
With this approach, you'll only need to ensure that the cursor file will be found in a particular location relative to your .EXE. Of course the same structure will need to exist both on your dev box and on target machines. Use MSBuild tasks in Visual Studio to copy your resource files to $(OutDir)\relative\path\to. For deployment to other machines, simply copy+paste the contents of your output folder, or create an installer that deploys files to the required folder structure.

Related

C#: opening a text file stored within the same project as the app

I managed to open a text file using an absolute path (in Visual Studio 2017) although if I change the location of my Solution folder the whole code would not work anymore as the actual physical path has changed and the code can not reference an existing location anymore.
I tried to create a text file within the same project and I would now like to open this file in my code, so if the location of the whole Solution changes the program can still work, would anyone be so kind to help me fix this issue?
I have also looked online for some different solution using code that references the current directory but I can't get my head around it as the current directory seems to be bin/debug and if I try to insert the file there the code doesn't recognize the location (also it doesn't look like a clean solution to me).
This is the code I am using so far in a WPF app, the whole purpose is to open the content of the text file containing countries listed line by line and to add them to a list box which will be displayed when a checkbox will be ticked.
private void listCountry_Initialized(object sender, EventArgs e)
{
listCountry.Visibility = Visibility.Hidden;
string path = "C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\StudentRecord\\country.txt";
if (File.Exists(path))
{
string[] myCountryFile = File.ReadAllLines(path);
foreach (var v in myCountryFile)
{
listCountry.Items.Add(v);
}
}
}
This is a great use case for OpenFileDialog Class.
Represents a common dialog box that allows a user to specify a filename for one or more files to open.
Here is the example of use, from the documentation.
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
Assuming C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\ is your project, and StudentRecord\\country.txt is a project folder and file in your project - you need change "Copy to Output Directory" to be "Always Copy" or "Copy If Newer" and "Build Action" to "Content" for the file in your project.
As you can see from the screenshot above, the folder structure for this content is created as well.
Then change your path assignment to be something like the following:
string path = string.Join(#"\", Application.ExecutablePath, #"StudentRecord\country.txt");
Clean and simple, place the file you want to open next to where the executable is generated, remember the executable path changes depending to if your project is in Debug or Release build mode. Now set:
string path = "country.txt";
By only providing a filename, the file is looked for in the same folder as the executable. Just remember that when you move the executable you must also move the file to the same place, but if you move the entire project folder then you're already set.
However, if you want to keep your file in a fixed location regardless of where you have your executable and/or VS project files, then the simplest path for it is:
string path = "C:\\country.txt";
This is an absolute path, but it's quite simple and very robust to changes, you would have to change the drive letter to break it and if C: is where your operating system files are then you probably won't do that.
If you don't like to have your files around in your root, you can always have a path like this:
string path = "C:\\ProjectNameFiles\\country.txt";
Or if you prefer to maintain a hierarchy of projects then you can use:
string path = "C:\\MyProjectsFiles\\ProjectName\\country.txt";
With this, every project can have a directory for the files it needs to open. These are all absolute paths, but are notably simpler than the one you posted, and they have a more fixed and organized structure.

Moving up a folder from the executable

I am trying to make a file path inside of the folder above the executable. For instance, I am wanting the variable TAGPATH to be the filepath to an executable in the folder C:\User\ApplicationFolder\tag_rw\tag_rw.exe while the application is in C:\User\ApplicationFolder\AppFiles. I want the application to be portable, meaning no matter the folder names it will retrieve the filepath of the application's executable then go to the parent folder and navigate into tag_rw\tag_rw.exe.
I basically want string TAGPATH = #"path_to_appfolder\\tag_rw\\tag_rw.exe"
Here is what I have tired so far (using the first answer How to navigate a few folders up? ):
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string TAGPATH = System.IO.Path.GetFullPath(System.IO.Path.Combine(appPath, #"..\"));
I am getting a run-time error ArgumentException with the description URI formats are not supported.
Is there an easier/better way to go about this?
Thank you!
Can you try this?
static void Main(string[] args)
{
string cur = Environment.CurrentDirectory;
Console.WriteLine(cur);
string parent1 = Path.Combine(cur, #"..\");
Console.WriteLine(new DirectoryInfo(parent1).FullName);
string parent2 = Path.Combine(cur, #"..\..\");
Console.WriteLine(new DirectoryInfo(parent2).FullName);
Console.ReadLine();
}
Navigation is limited to absolute and relative types. I think you mean to navigate to parent directory regardless of whole application location.
Maybe you try relative path
string TAGPATH = "..\\tag_rw\\tagrw.exe"

Visual studio project directory issue

I'm writing to a text folder which is in a folder within my project but I can't seem to get to it without writing the absolute complete path as it is on my computer which is fine on this computer but when I want to take it elsewhere I can't have that as the drives are different etc.
Here is a screenshot of the lines I'm using to get it to post to the directory on the right.
The file I'm trying to access is in a folder called AdminAccount and is called User.txt. it works fine as you can see from the commented directory link as a direct path but when I try with the directory string in use it does not work.
http://i.imgur.com/hAV55W0.png
Any help how to get around this? I tried all sorts, I tried doing
private string[] getLines = System.IO.File.ReadAllLines(#"\AdminAccount\User.txt");
private string[] getLines = System.IO.File.ReadAllLines(#"..\AdminAccount\User.txt");
No joy.
You can use,
string rootPath = Environment.CurrentDirectory;
string filePath = Path.Combine(rootPath,#"..\..\AdminAccount\User.txt");
private string[] getLines = System.IO.File.ReadAllLines(#filePath);
..\ is used to access a top level folder in the hierarchy. you can keep on adding ..\ to move up in the hierarchy.
Ex:
string path1 = #"C:\Users\Documents\Visual Studio 2010\Projects\Test\Test\bin\Debug"
string newPath = Path.Combine(path1, #"..\..\AdminAccount\User.txt");
new path would return
C:\Users\Documents\Visual Studio 2010\Projects\Test\Test\AdminAccount\User.txt
You just have to set the property "Copy to Output Directory" of the "User.txt" file to "Copy allways" or "Copy if newer".
Now you can read the lines as below
string[] getLines = File.ReadAllLines(
Path.Combine(Application.StartupPath, "AdminAccount", "User.txt"));

Write a text file to a sub-folder

I am trying to write out a text file to: C:\Test folder\output\, but without putting C:\ in.
i.e.
This is what I have at the moment, which currently works, but has the C:\ in the beginning.
StreamWriter sw = new StreamWriter(#"C:\Test folder\output\test.txt");
I really want to write the file to the output folder, but with out having to have C:\ in the front.
I have tried the following, but my program just hangs (doesn't write the file out):
(#"\\Test folder\output\test.txt");
(#".\Test folder\output\test.txt");
("//Test folder//output//test.txt");
("./Test folder//output//test.txt");
Is there anyway I could do this?
Thanks.
Thanks for helping guys.
A colleague of mine chipped in and helped as well, but #Kami helped a lot too.
It is now working when I have:
string path = string.Concat(Environment.CurrentDirectory, #"\Output\test.txt");
As he said: "The CurrentDirectory is where the program is run from.
I understand that you would want to write data to a specified folder. The first method is to specify the folder in code or through configuration.
If you need to write to specific drive or current drive you can do the following
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
string path = diveLetter + #"Test folder\output\test.txt";
StreamWriter sw = new StreamWriter(path);
If the directory needs to be relative to the current application directory, then user AppDomain.CurrentDomain.BaseDirectory to get the current directory and use ../ combination to navigate to the required folder.
You can use System.IO.Path.GetDirectoryName to get the directory of your running application and then you can add to this the rest of the path..
I don't get clearly what you want from this question , hope this get it..
A common technique is to make the directory relative to your exe's runtime directory, e.g., a sub-directory, like this:
string exeRuntimeDirectory =
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string subDirectory =
System.IO.Path.Combine(exeRuntimeDirectory, "Output");
if (!System.IO.Directory.Exists(subDirectory))
{
// Output directory does not exist, so create it.
System.IO.Directory.CreateDirectory(subDirectory);
}
This means wherever the exe is installed to, it will create an "Output" sub-directory, which it can then write files to.
It also has the advantage of keeping the exe and its output files together in one location, and not scattered all over the place.

Save/retrieve a file in a project directory, not the output directory

I'm creating a simple .NET console application where I want to save a file in a folder that's part of the root project, like so: SolutionName.ProjectName\TestData\. I want to put test.xml into the TestData folder. However, when I go to save my XDocument, it saves it to SolutionName.ProjectName\bin\x86\Debug Console\test.xml.
What do I need to do to save or retrieve the file in a folder that is a child of project directory?
Your console application is, once compiled, not really related to your Visual Studio solution anymore. The best way is probably to simply 'feed' the output path to your application as an command line argument:
Public Sub Main(args as String())
' don't forget validation: handle situation where no or invalid arguments supplied
Dim outputFile = Path.Combine(args(0), "TestData", "test.xml")
End Sub
Now you can run your application like so:
myapp.exe Path\To\SolutionFolder
I've seen this before but never actually tried it out. Did a quick search and dug this up:
System.AppDomain.CurrentDomain.BaseDirectory
Give that a shot instead of Application.StartupPath for your console app.
You can use the System.IO namespace to get your directory relative to your exe:
var exeDirectory = Application.StartupPath;
var exeDirectoryInfo = new DirectoryInfo(exeDirectory);
var projectDirectoryInfo = exeDirectoryInfo.Parent.Parent.Parnet; // bin/x86/debug to project
var dataPath = Path.Combine(projectDirectoryInfo.FullName, "TestData");
var finalFilename = Path.Combine(dataPath, "test.xml");

Categories

Resources