简体   繁体   English

C#控制台应用程序在通过命令行调用时不会写入文件,但否则会写入文件

[英]C# Console App doesnt write to file when called by command line but does otherwise

I have a small console app that takes parameters. 我有一个带有参数的小型控制台应用程序。 Througout i use a method to throw some info into a file 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 by command line invocation, the program runs but the log file isnt amended. 但是,当通过命令行调用运行该程序时,该程序运行,但未修改日志文件。

If the app is run by launching via explorer or debugging in visual studio the logging works. 如果该应用是通过资源管理器启动或在Visual Studio中调试运行的,则日志记录将起作用。

Any ideas? 有任何想法吗?

尝试定义完整的写入路径,例如: C:\\Users\\user\\Documents\\log.txt

new StreamWriter("log.txt", true) writes to the current working directory, which could be anywhere at all, including network shares or places you do not have write access to. new StreamWriter("log.txt", true)写入当前工作目录,该目录可以在任何地方,包括网络共享或您没有写访问权的位置。 Always specify the full path to any files. 始终指定任何文件的完整路径。 If you want to write to a file you need to make sure you write to a place you have access to. 如果要写入文件,则需要确保写入具有访问权限的位置。 Do not just run your app 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM