John.Smith
John.Smith

Reputation: 87

How can I get the file path for a file I only know the name of? C#

So I'm making a Tic Tac Toe application and have created a Text file linked to the program to hold the following information:

I know the timer is redundant for a quick game like Tic Tac Toe but I'll use it in the future for other programs.

I want to do this using the program so it can be transferred to any computer and still be able to access the file without the user having to input it.

The code I've tried is:

string file_name = Path.Combine(Environment.CurrentDirectory, "Tic Tac Toe\\HighScores.txt");

But this just looks in the Debug folder, where the file isn't located. The application is entirely a console application.

Upvotes: 1

Views: 85

Answers (2)

AntDC
AntDC

Reputation: 1917

Perhaps have a configuration file for your application and store the directory name in there.

An old example from MS, but should still be applicable...

How to store and retrieve custom information from an application configuration file by using Visual C#

Upvotes: 1

Noli
Noli

Reputation: 614

Try to dedicate the file in a fixed sub directory:

\TicTacToe.exe \settings\settings.cfg

So the path is dependent of your executable file.

You'll fetch the directory by calling Directory.GetCurrentDirectory()

You can set a desired directory by setting Environment.CurrentDirectory

A common way to handle this case is the one described above.

Another would be to use user specifiy directories like the %appdata% path and create a dedicated directory there.

%appdata%\TicTacToe\settings.cfg

Everytime your application starts it should lookup the folder %appdata%\TicTacToe\

If it is present, your application has been executed with this user. If not, just create a new one, so we know it's the first run.

You can get the %appdata% path by calling

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Example of what i would have done

private void setUp(){
string filename = "settings.cfg";
string dir = "TicTacToe";
string appdata =Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullpath = Path.Combine(Path.Combine(appdata,dir),filename);

//check if file exists, more accurate than just looking for the folder
if(File.Exists(fullpath )){
//read the file and process its content
}else{
Directory.CreateDirectory(Path.Combine(appdata,dir)); // will do nothing if directory exists, but then we have a bug: no file, but directory available
using (FileStream fs = File.Create(fullpath))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
 }
 }

Hope it helped.

Upvotes: 1

Related Questions