I'm using steamwriter to write X and Y coordinates on mouse click to a text file. It does work but when I click more than once the coordinates in the text file are overwritten with the new coordinates. This is probably a simple question but how do I get it to write all new coordinates to a new line?
Here's my code:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespaceWindowsFormsApplication1
{
publicpartialclassForm1 : Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidForm1_MouseClick(object sender, MouseEventArgs e)
{
string path = @"C:\coordinates.txt";
StreamWriter sw = new StreamWriter(path);
string bufferOne = ("X = " + e.X + ", Y = " + e.Y);
sw.WriteLine(bufferOne);
sw.Close();
sw.Dispose();
}
}
}
Cheers!
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Sam HobbsRank #108 · 20.5K reputationPosted Jun 21, 2010, 11:28 AM EDT
0
Open the file once and don't close it until the form is closed. In other words, don't do "new StreamWriter" each time you do a WriteLine and don't do the Close or Dispose each time you do a WriteLine. Alternatively, insted of:
Sam HobbsRank #108 · 20.5K reputationPosted Jun 21, 2010, 11:28 AM EDT
StreamWriter sw = new StreamWriter(path);
Use:
StreamWriter sw = new StreamWriter(path, true);