简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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