0

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);
                }
            }
        }
David Ciocoiu
  • 113
  • 1
  • 2
  • 6
  • hmm... "...it doesn't look like a clean solution to me" this question should be flagged and closed based on it being a duplicate question and your too-broad desire for a **clean** solution. – Brett Caswell Oct 27 '19 at 21:41
  • also, if you're having problems understanding the answers in those questions, you can probably just invoke the one who answered it... it may help improve their answer – Brett Caswell Oct 27 '19 at 21:45

3 Answers3

1

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;
}
tymtam
  • 31,798
  • 8
  • 86
  • 126
0

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.

Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21
  • clarify "place the file", clarify "next to".. how does this solution differ to OP always ensuring the file exists at `"C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\StudentRecord\\country.txt"`? i.e. manual operations outside of the program and assuring some convention for usage? – Brett Caswell Oct 27 '19 at 21:53
  • @BrettCaswell "Place and next to" means to have the file in the same place as the executable. If he moves the exec to another place then he has to do the same with file, but that's just selecting and cutting/pasting them there is no auto way for this. As far as conventions go, do you know of any software that does not make conventions as to where its files are? There are only two filepaths, absolute and relative, the most flexible is relative, and of the relative type the solution I gave is the simplest one. With absolute path type you always end up changing the path when you move the file. – Javier Silva Ortíz Oct 27 '19 at 22:06
  • Plus, the OP just wants a solution for not having to change the filepath variable whenever he changes the project folder location. Honestly, @BrettCaswell, what's wrong with it, share the insight? – Javier Silva Ortíz Oct 27 '19 at 22:08
  • Maybe @BrettCaswell the overly broad scope and bit obscurity of the question is making us confused? – Javier Silva Ortíz Oct 27 '19 at 22:14
  • 1
    Thank you it works! I would have preferred a more flexible solution instead of moving the file to the executable folder, like having a specific folder with any potential file I might have to open and then have a code that works on that. Although your solution is very clean! :) – David Ciocoiu Oct 29 '19 at 10:44
0

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.

Screenshot of Project and Properties with Debug Output shown

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");
Brett Caswell
  • 1,486
  • 1
  • 13
  • 25
  • with that said, you could have always added a `FileOpenDialog` to your winform. It depends on use case and scenarios, but the dialog should exist anyway, in the event the file is not found to exist in your check. – Brett Caswell Oct 27 '19 at 22:28