Chris Devine
Chris Devine

Reputation: 67

C# File directory issue

I have created a high score file for my game and I am having problems reading it.

When I change computers my USB drive changes letter .eg from drive E to drive G.

This is causing problems with reading the file. (as I use string path = @"g:\Scores.txt";)

So my question is.... can I set a default path to the program location??

My current code:-

string path = @"g:\Scores.txt";
            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    sb.Append(sr.ReadLine());
                }
            }

any help is appreciated.

Upvotes: 0

Views: 78

Answers (3)

Fernando Pap
Fernando Pap

Reputation: 94

You should use your application path, not an absolute path. You may do something like this:

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath);

Upvotes: 0

pascx64
pascx64

Reputation: 984

If your program is in the same folder as the file ( Eg. in G:\ ), then you can simply access the file with his name : `path = "Scores.txt". In that case there is no need to know where is the file

Upvotes: 0

Michael Gunter
Michael Gunter

Reputation: 12811

Is the game on your USB drive as well? Do you want to save the file in the same directory as the game, or in a directory somewhere around it? Do something like this:

using System;
using System.IO;
using System.Reflection;
...
string thisAsmFile = Assembly.GetExecutingAssembly().Location;
string thisAsmDir = Path.GetDirectoryName(thisAsmPath);
string highScoreFile = Path.Combine(thisAsmDir, "scores.txt");

Upvotes: 3

Related Questions