L.redir
L.redir

Reputation: 65

File exists, if statement checks, wont return correct output if file doesnt exist, C#

I have a nested if-else statement that is checking the contents of a folder I have that contains other txt files. This method either creates new txt files or denies access if they already exist in the folder.

The trouble I am having is with the checks if the file exists in the folder. Currently no matter what I do, the command will always return "Filename already exists" even if it doesn't exist.

If the file does not exist then the program should go down to the else statement and then create the new file

protected void create(string command, string param1)
{
    // creates an empty file w/ default permissions
    // if file already exists then error message displayed in console

    //checks name of the file, checks if its exists, and if clear, creates the file
    if (param1 == "accounts.txt" || param1 == "audit.txt" || param1 == "groups.txt" || param1 == "files.txt")
    {
        Console.WriteLine("Cannot use this filename");
        Console.Read();
        return;
    }
    else if (File.Exists(@"C:\Files\"))
    {
        Console.WriteLine("Filename already exists");
        Console.Read();
        return;
    }
    else
    {
        string path = Path.Combine(@"C:\Files\", param1);
        using (StreamWriter sw = File.AppendText(path))
        {
            Console.Write("create " + param1 + "");
            string path2 = "C:\\Files\\audit.txt";
            using (StreamWriter sw2 = File.AppendText(path2))
            {
                sw2.WriteLine("File " + param1 + " with owner and default permissions created"); //append name of current login from memory
            }
            Console.ReadLine();
        }
    }
}

Upvotes: 1

Views: 1092

Answers (2)

user1108948
user1108948

Reputation:

You didn't provide the file name in the code. The string @"C:\Files\") is not a file name, it is a directory.

You can use something like.

internal static bool FileOrDirectoryExists(string name)
{
    return (Directory.Exists(name) || File.Exists(name));
}

To call the method, you have to pass the valid file name.

var name = Path.Combine( @"C:\Test","MyFile.txt");
var ifFileExist = FileOrDirectoryExists(name);

Upvotes: 1

Sam Trost
Sam Trost

Reputation: 2173

This block here is saying if the File doesn't exist, then write to the console 'File already exists'

else if (!File.Exists(@"C:\Files\"))
            {
                Console.WriteLine("File already exists");
                Console.Read();
                return;
            }

Also note that you're using File.Exists on a directory, and not actually looking at a specific file.

See also Directory.Exists

MSDN - Directory Exists method

Upvotes: 2

Related Questions