写入txt文件 [英] writing to a txt file

查看:74
本文介绍了写入txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有4个值的数组(鼠标坐标.当我单击鼠标左键时,它将把值发送到该数组

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);
            Clipboard.SetText(coords);
            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());
            tw.Close();



我遇到的问题是它只写一次.就像我两次单击鼠标左键一样,它需要imgcoor [0-3].我想做的是重复执行此操作,每2次单击将在一行上,但我无法使其正常工作.任何想法和帮助表示赞赏.

因此,当我第一次单击它时,应该像497,300,499,300一样写入xk24.txt
当我再次点击左键时,它应该记录到第二行.

似乎它记录了一次并关闭了文件,并且不会重写:(



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 :(

推荐答案

当然,它确实会-每次您写StreamWriter都会创建一个新文件叫它!
使用File.AppendText方法:
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());
        }  

此外,将您的文件访问权限封装在using块中是一个非常好的主意-在文件被处置之前,可能无法再进行写入.

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.


我会使用而是使用File.AppendAllText或File.WriteAllText,因为它更干净,并且总是在其自身之后进行清理.
I would use File.AppendAllText or File.WriteAllText instead, because it''s cleaner, and it always cleans up after itself.


您应将文本附加到文件中.像下面
那样更改您的代码
You should append the text to the file. Change your code like following

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



这里的第二个参数是append



Here the second argument is append


这篇关于写入txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆