1.判断文件是否存在,若存在则打开写入,否则创建文件并写入
//写txt文件
public static void WriteText(string TempSTR,string TempPath)
{
//实例化一个StreamWriter-->与fs相关联
Definition.severPath = @"D:\source\CIM_OPTTRANSFER\" + Definition.PJ_Data.ID + ".txt";
//创建文件
if (!File.Exists(Definition.severPath))
{
FileStream fs = new FileStream(Definition.severPath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.WriteLine(TempSTR);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
else
{
FileStream fs = new FileStream(Definition.severPath, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.WriteLine(TempSTR);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
}
2.调用方法写入内容,其中回车用\r\n
iniFile.WriteText("Data : "+DateTime.Now.ToString().Substring(0,10)+"\r\n"
+ "Time : " + DateTime.Now.ToString().Substring(11, 8) + "\r\n"
+ "Model No. : " + Definition.PJ_Data.Model + "\r\n"
+ "Lot No. : " + "\r\n"
+ "Product S/N : " + Definition.PJ_Data.ID + "\r\n"
+ "Pass/Fail : " + Definition.PJ_Data.okng + "\r\n"
+"\r\n"
+ "--------------------------------- Test Result -------------------------------------"
, Definition.severPath);
3.txt文件中追加内容
public static void WriteDataGridViewTxt(string TempSTR, string TempPath)
{
//string TempPath;// As String
//TempPath = AppDomain.CurrentDomain.BaseDirectory + "\\cimlog.csv"; // .Path + "\cimlog.csv"
//Open TempPath For Append As #1
// Print #1, TempSTR
//Close #1
//FileStream fs = new FileStream(TempPath, FileMode.Append);
//实例化一个StreamWriter-->与fs相关联
Definition.severPath = @"D:\source\CIM_OPTTRANSFER\" + Definition.PJ_Data.ID + ".txt";
StreamWriter sw = File.AppendText(Definition.severPath);
//开始写入
sw.WriteLine(TempSTR);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
}
4.调用追加TXT方法,并将dataGridView控件内容写入txt
for (int i = 0;i <dataGridViewStep.RowCount-1;i++)
{
for (int j = 0; j < dataGridViewStep.ColumnCount; j++)
{
if (this.dataGridViewStep.Rows[i].Cells[j].Value != null)
{
iniFile.WriteDataGridViewTxt(this.dataGridViewStep.Rows[i].Cells[j].Value.ToString(), Definition.severPath);
}
}
}
文章来源地址https://www.toymoban.com/news/detail-613661.html
文章来源:https://www.toymoban.com/news/detail-613661.html
到了这里,关于C#创建文件写入及追加内容的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!