Click here to Skip to main content
15,843,031 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an array with 4 values(mouse coordinates. When i left click it sends the values to the array

Point p2 = PointToClient(Cursor.Position);
            string coords = string.Format("({0},{1})", p2.X, p2.Y);
            imgcoor[0] = p2.X;
            imgcoor[1] = p2.Y;
            imgcoor[2] = p2.X;
            imgcoor[3] = p2.Y;
            TextWriter tw = new StreamWriter("xk24.txt");
            tw.WriteLine(imgcoor[0].ToString() + "," + imgcoor[1].ToString() + "," + imgcoor[2].ToString() + "," + imgcoor[3].ToString());

The problem I am having is it only writes once. Like I hit on left click twice and it takes imgcoor[0-3]. What I want to do is doing this operation repeatedly and each 2 clicks will be on one line but I can't get it to work. Any ideas and help appreciated.

So when i first click it should write to xk24.txt like 497,300,499,300
and when i hit left click again it should record it to the second line.

It seems like it records it once and closes the file and doesn't rewrite :(
TolgaCiftci 21-May-10 8:45am    
Thank you for all your help I got my answers.
OriginalGriff 21-May-10 10:08am    
In answer to your comment "what is the difference between File.AppendText(path) and StreamWriter(path, true)".
In practice, none - the probability is that the AppendText will call StreamWriter with a "true" parameter. I would use the AppendText because it is more obvious to a casual read than "true" on the end of a StreamWriter command. Others will, I am sure, disagree!

Of course it does - the StreamWriter creates a new file each time you call it!
Use the File.AppendText method:
using (StreamWriter sw = File.AppendText("xk24.txt")) 
        sw.WriteLine(imgcoor[0].ToString() + "," + imgcoor[1].ToString() + "," + imgcoor[2].ToString() + "," + imgcoor[3].ToString());
Plus, it is a VERY good idea to encapsulate your file access in a using block - until the file is disposed, it may not be available for more writing.
Share this answer
TolgaCiftci 21-May-10 8:36am    
Sorry I am new to programming what exactly the difference between appendText and StreamWriter? just before you answered I added a boolean and it worked but I want to learn the difference. TextWriter

tw = new StreamWriter("xk24.txt",true); This is what i did and worked but your code also works so what are the differences?
I would use File.AppendAllText or File.WriteAllText instead, because it's cleaner, and it always cleans up after itself.
Share this answer
You should append the text to the file. Change your code like following

TextWriter tw = new StreamWriter("xk24.txt",true);

Here the second argument is append
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900