I have a small console ứng dụng that takes parameters. Througout i use a method lớn throw some info into a tệp tin as a log. Very simple:

        static void Log(string str)
        {
            using (StreamWriter sw = new StreamWriter("log.txt", true))
            {
                sw.WriteLine(str);
            }
        }

However, when this program is run rẩy by command line invocation, the program runs but the log tệp tin isnt amended.

If the ứng dụng is run rẩy by launching via explorer or debugging in visual studio the logging works.

Any ideas?

asked Mar 11, 2019 at 16:28

3

new StreamWriter("log.txt", true) writes lớn the current working directory, which could be anywhere at all, including network shares or places you vì thế not have write access lớn. Always specify the full path lớn any files. If you want lớn write lớn a tệp tin you need lớn make sure you write lớn a place you have access lớn. Do not just run rẩy your ứng dụng as Administrator, that opens all kinds of security holes.

You probably want something like:

var p = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "myAppName");
if (!Directory.Exists(p)) Directory.CreateDirectory(p);
using (var sw = new StreamWriter(Path.Combine(p, "log.txt"), true)
{
    sw.WriteLine(str);
}

answered Mar 11, 2019 at 16:58

2

Try lớn define the full write path like: C:\Users\user\Documents\log.txt

Joel Coehoorn

415k114 gold badges577 silver badges812 bronze badges

answered Mar 11, 2019 at 16:38