关于将数据写入文件的问题,高手帮个忙!
本人已将写入文件的代码写好,但是在保存文件的时候,有一个保存文件对话框,可以新建一个txt保存,但无法保存在已经存在的txt文件中(除了覆盖),现希望不仅可以通过新建txt保存,也可以保存到已经存在的txt中,并将数据保存到已存在内容的下一行,该怎么修改?希望高手帮我的程序修改一下。代码如下:
private void 保存数据_Click(object sender, EventArgs e)
{
if ((待定点X.Text.Trim() != "") && (待定点Y.Text.Trim() != ""))//确认待定点的X,Y坐标已被计算出来
{
if (待定点名.Text == "")
MessageBox.Show(this, "请输入待定点名!", "提示");//确认应经给待定点命名
else
{
SaveFileDialog sf = new SaveFileDialog();
sf.Title = "保存文件";
sf.Filter = "txt文件|*.txt|所有文件|*.*";//将计算结果保存为txt类型
if (sf.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(sf.FileName, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
string[] tempStr = new string[3];
tempStr[0] = 待定点名.Text;
tempStr[1] = Convert.ToString(待定点X.Text);
tempStr[2] = Convert.ToString(待定点Y.Text);
for (int i = 0; i < tempStr.Length; i++)
{
if (i > 0)
{
sw.Write(",");
}
sw.Write(tempStr[i]);
}
sw.Flush();
sw.Close();
fs.Close();
}
}
}
else
{
MessageBox.Show(this, "请先计算!", "提示");
}
} --------------------编程问答-------------------- 上面我写的太多了,这部分是主要的:
{
SaveFileDialog sf = new SaveFileDialog();
sf.Title = "保存文件";
sf.Filter = "txt文件|*.txt|所有文件|*.*";//将计算结果保存为txt类型
if (sf.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(sf.FileName, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
string[] tempStr = new string[3];
tempStr[0] = 待定点名.Text;
tempStr[1] = Convert.ToString(待定点X.Text);
tempStr[2] = Convert.ToString(待定点Y.Text);
for (int i = 0; i < tempStr.Length; i++)
{
if (i > 0)
{
sw.Write(",");
}
sw.Write(tempStr[i]);
}
sw.Flush();
sw.Close();
fs.Close();
}
} --------------------编程问答-------------------- 用AppendText就可以追加的。
using System;--------------------编程问答-------------------- 创建文件流时有几种模式供选择
using System.IO;
class Test
{
public static void Main()
{
FileInfo fi = new FileInfo(@"c:\temp\MyTest.txt");
// This text is added only once to the file.
if (!fi.Exists)
{
//Create a file to write to.
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// This text will always be added, 易做图 the file longer over time
// if it is not deleted.
using (StreamWriter sw = fi.AppendText())
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
//Open the file to read from.
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
Create,CreateNew,Append之类的,对你要的写入分别选择合适的模式即可实现清空原有文件写入和在原有文件进行追加 --------------------编程问答-------------------- 正解 --------------------编程问答-------------------- 2楼正解
补充:.NET技术 , C#