[PROBLEM]File.Exist and !File.Exist, does not behave like I want it to.

  • Thread starter Thread starter NewDevO1
  • Start date Start date
N

NewDevO1

Guest
To clarify,

I have a "fake user database" where a "admin" can create a file, a text file.

So when the admin is entering a name for that file, I need a script to check if that file exists.

Then, if it turns out to be true proceed to alert the admin with a message in Console.

But if the script doesn't find anything, it will be false, so proceed to create that new file with that new name.

So here is my code;

Console.WriteLine ("Create a text file to store users in.");

Console.WriteLine ("In what location do you want to put this file in?");
Console.WriteLine ("Location: ");
location = Console.ReadLine ();

Console.WriteLine ("Text file name: ");
txtFile = Console.ReadLine ();

string path = location + txtFile;

using (var sWriter = new StreamWriter (path , true))
{

if (File.Exists (path))
{
Console.WriteLine ("FAIL! FILE ALREADY EXIST! DELETE THE EXISTING ONE, OR CHOSE A DIFFERENT NAME.");
sWriter.Close ();

}
else if(!File.Exists(path)) {

File.Create (path);
Console.WriteLine ("Success! File {0} has been created in {1}" , txtFile , location);
sWriter.Close ();
}


}

So, the output will only print out the error message no matter what. If I chose another name, it still outputs that message. Don't know why and how I can fix this.

Continue reading...
 
Back
Top