0

So as the question says I have a program set up to start at windows startup, but it doesn't read the .txt next to it, when I launch the program it does.

bool cdexist = File.Exists("cd.txt");
if (cdexist)
{
   StreamReader sr = new StreamReader("cd.txt");
   time = Convert.ToInt32(sr.ReadLine());
   sr.Close();
   if (time != 0)

   {}.....rest of the code 

Whats could be the issue?

Edit: part where I write to the file

{

 timeleft = time - i;
 label1.Text = timeleft.ToString();
 StreamWriter sw = new StreamWriter("cd.txt");
 sw.Write(timeleft);
 sw.Close();

 i++;

}

EDIT I am unable to solve the issue, I tried recreating what happens when the PC starts, and as soon as I'm at the desktop I start the program and it's working, but when the system does it automatically with windows it doesn't seem to read the .txt.

hobuci
  • 51
  • 6
  • What does `the .txt next to it` mean? Do you mean a command line argument? – Ňɏssa Pøngjǣrdenlarp Feb 14 '16 at 01:04
  • the .txt is just storing a number, rewriting that number every time the value changes (and closing the file with streamwriter immediately), what may cause this issue is that my program forces the PC to shutdown, is it possible that the txt is not saved correctly? – hobuci Feb 14 '16 at 01:25
  • You didn't flush the stream when writing to the file. Try adding `sw.Flush()` before `sw.Close()`. – DDoSolitary Feb 14 '16 at 01:44
  • @Stalker `StreamWriter.Close` invokes `StreamWriter.Dispose`, which invokes `StreamWriter.Flush` http://referencesource.microsoft.com/#mscorlib/system/io/streamwriter.cs,ab19992c30648b1d – Preston Guillot Feb 14 '16 at 03:38

1 Answers1

2

File paths like "cd.txt" are always interpreted relatively. And usually they are interpreted as relative to the current working directory. When you just execute your program e.g. from your Windows Explorer, then the working directory is the executable’s location. So it will look for the file directly next to the application.

However, when executed in a different fashion, it’s likely that the working directory is very different. So if you expect the file to be located next to the executable, you should change your program to look for it there. For example like this:

string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cd.txt")
bool cdexist = File.Exists(filePath);
// …

Check this question for other ways to get the correct directory.

Community
  • 1
  • 1
poke
  • 369,085
  • 72
  • 557
  • 602