0

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.

3 Answers3

3

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");
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58
  • It's worth noting that the other comments and answers are only partially correct. A relative path name will be resolved from the current working directory, not the directory of the application. If you double-click an .exe, the current working directory will *usually* be the same directory as the application. However, there are lots of situations when this isn't the case (running from a UNC directory, for example). The method I've shown above is guaranteed to get you the location of the running executable. – Michael Gunter Feb 12 '15 at 19:47
0

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

pascx64
  • 904
  • 16
  • 31
0

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);
Fernando Pap
  • 74
  • 10