Mario
Mario

Reputation: 15

C# application doesn't create file if called from command prompt

I have a simple C# console application which writes some information to a text file. The application works fine when opened from desktop (by clicking on the .exe file). However when I open the application via command prompt, the console window will open normally but the application won't write anything to the text file (the other code functions work normally in the console window).

Fyi I need to open the application via command prompt because later on the exe application will be put on server and called from a php script (using exec or shell_exec).

I assume this might be an issue with write permissions or something, but no error is thrown at any point so I'm not sure. Any ideas please?

My code:

    static void Main(string[] args)
    {
        string arg="";
        try
        {
            arg = args[0];
        }
        catch { 
        }
        using (StreamWriter outputWriter = File.AppendText(@"C:\Archive\test.txt"))
        {
            outputWriter.WriteLine("arg="+arg);
        }
        Console.WriteLine("Test");
        Console.ReadLine();
    }

Upvotes: 0

Views: 889

Answers (2)

Mario
Mario

Reputation: 15

Well I don't know what happened, but I'm trying again now via command prompt and the code works as expected. It could be that I removed any hidden errors as I cleaned up the code to post it here. Ugh.. :-)

Upvotes: 0

Fabio Salvalai
Fabio Salvalai

Reputation: 2509

when you run your application from the commandline, the current directory depends on your location in the prompt.

when running your .exe make sure you run it from the same directory as the file you want to write to.

If this solves the problem, then you'll need to write code to handle the case where the file to write to is not in the current directory, perhaps set it by code.

Upvotes: 1

Related Questions