简体   繁体   English

C#从Windows窗体打印到文本文件

[英]C# Print to a text file from a windows form

I was able to get this code to work in a console application but I am currently working in a windows form. 我能够获得此代码以在控制台应用程序中工作,但当前正在Windows窗体中工作。 I changed the output to console application but this still did not work. 我将输出更改为控制台应用程序,但这仍然无法正常工作。

        string path = @"C:\Users\rbc658\Trajectory.txt";
        if (!File.Exists(path))
        {
            File.Create(path);
            TextWriter txt = new StreamWriter(path);
            txt.WriteLine("Hello");
            txt.Close();
        }
        else if (File.Exists(path))
        {
            using (var txt = new StreamWriter(path, true))
            {
                txt.WriteLine("Hello");
                txt.Close();
            }
        }

"Close" "Create" and "WriteLine" are not highlighted like they are in the above text. “关闭”,“创建”和“写行”未像上面的文本中突出显示。 I am using system.io. 我正在使用system.io。 What is different about forms and console application that would prevent this from working? 表单和控制台应用程序有什么不同之处会阻止其工作?

It is more elegant for you to create a function to call to write something to a text file, like this 对于您来说,创建一个函数来向文本文件中写入内容的调用更为优雅

This code below worked for me: 下面的代码为我工作:

    private void Form1_Load(object sender, EventArgs e) // for example run this code when form loads
    {
        string path = @"C:\Users\Luka\Desktop\Trajectory.txt"; // your path to a text file
        string text = "Hello"; // some text to write to a text file
        Write(text, path, File.Exists(path)); // we are passing File.Exists(path) as a boolean to see wether or not to append text to a file
    }
    private void Write(string text, string path, bool file_exists)
    {
        //if File.Exists(path) is true, streamwriters second argument is true, so it appends
        //else the argument is false and it does not append
        StreamWriter txt = new StreamWriter(path, file_exists); // creates new object type StreamWriter with 2 arguments
        //1. path to a file
        //2. boolean to see wether or not to append the text to a file
        txt.WriteLine(text); // writes text line to a file
        txt.Dispose(); // disposes streamwriter
    }

All explanation is displayed as comments in the code so you can copy it when testing the program. 所有解释都显示为代码中的注释,因此您可以在测试程序时将其复制。

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

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