C# 如何在不影响现有行的情况下将新行添加到现有CSV文件中
我想在第一行插入新的两行,而不影响CSV文件中的现有数据 例如: 现有CSV文件格式:C# 如何在不影响现有行的情况下将新行添加到现有CSV文件中,c#,C#,我想在第一行插入新的两行,而不影响CSV文件中的现有数据 例如: 现有CSV文件格式: Name Address Value -------------------------------- abc India 123 XXX USA 456 需要在现有CSV文件列标题之前插入新行。 例如: 我的现有代码用于创建CSV文件&使用此代码,我只能创建以下列和行: Name Address Val
Name Address Value
--------------------------------
abc India 123
XXX USA 456
需要在现有CSV文件列标题之前插入新行。
例如:
我的现有代码用于创建CSV文件&使用此代码,我只能创建以下列和行:
Name Address Value
--------------------------------
abc India 123
XXX USA 456
但需要在行上方添加两行
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public class CreateCSVFile
{
#region Create .csv File ANDON - DASHBOARD
public void CreateFile(HistorianData objHistorian)
{
try
{
CreateCSVFile obj = new CreateCSVFile();
StringBuilder sb = new StringBuilder();
DataTable dt = obj.GetData(objHistorian);
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
sb.Append(obj.FormatCSV(dr[dc.ColumnName].ToString()) + ",");
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
}
//Create .csv File:
string fileName = objHistorian.getTagName + "_" + "_" + DateTime.UtcNow.ToString("yyyy-MM-ddTHH_mm_ssZ") + ".csv";
string path = @"C:\Documents\" + fileName;
if (!File.Exists(path))
{
DataTableToCreateCSVFile(dt, path);
}
}
catch (Exception ex)
{
Console.WriteLine("Error :" + ex.StackTrace, ex.Message);
}
}
public DataTable GetData(HistorianData fields)
{
DataTable dt = new DataTable();
dt.Columns.Add("Tagname", typeof(string));
dt.Columns.Add("TimeStamp", typeof(string));
dt.Columns.Add("Value", typeof(string));
dt.Columns.Add("DataQuality", typeof(string));
dt.Rows.Add(fields.getTagName, fields.timeStamp, fields.getPropertyValue, fields.dataQuality);
return dt;
}
public string FormatCSV(string input)
{
try
{
if (input == null)
return string.Empty;
bool containsQuote = false;
bool containsComma = false;
int len = input.Length;
for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
{
char ch = input[i];
if (ch == '"')
containsQuote = true;
else if (ch == ',')
containsComma = true;
}
if (containsQuote && containsComma)
input = input.Replace("\"", "\"\"");
if (containsComma)
return "\"" + input + "\"";
else
return input;
}
catch
{
throw;
}
}
public void DataTableToCreateCSVFile(DataTable dtDataTable, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
//headers
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
sw.Write(dtDataTable.Columns[i]);
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtDataTable.Rows)
{
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
#endregion
}
public class HistorianData
{
public string getTagName { get; set; }
public DateTime timeStamp { get; set; }
public string dataQuality { get; set; }
public string getPropertyValue { get; set; }
}
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.IO;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
命名空间Windows窗体应用程序1
{
公共类CreateCSVFile
{
#区域创建.csv文件ANDON-仪表板
public void CreateFile(HistorianData objHistorian)
{
尝试
{
CreateCSVFile obj=新建CreateCSVFile();
StringBuilder sb=新的StringBuilder();
DataTable dt=obj.GetData(objHistorian);
foreach(数据行dr在dt.行中)
{
foreach(数据列dc在dt.列中)
sb.Append(obj.FormatCSV(dr[dc.ColumnName].ToString())+“,”;
移除(sb长度-1,1);
(某人);
}
//创建.csv文件:
字符串文件名=objHistorian.getTagName+“”+“”+DateTime.UtcNow.ToString(“yyyy-MM-ddTHH_-MM_-ssZ”)+“.csv”;
字符串路径=@“C:\Documents\”+文件名;
如果(!File.Exists(path))
{
DataTableToCreateCSVFile(dt,路径);
}
}
捕获(例外情况除外)
{
Console.WriteLine(“错误:+ex.StackTrace,ex.Message”);
}
}
公共数据表GetData(历史和数据字段)
{
DataTable dt=新的DataTable();
添加(“标记名”,类型(字符串));
添加(“时间戳”,typeof(字符串));
添加(“值”,类型(字符串));
添加(“数据质量”,类型(字符串));
添加(fields.getTagName、fields.timeStamp、fields.getPropertyValue、fields.dataQuality);
返回dt;
}
公共字符串格式CSV(字符串输入)
{
尝试
{
如果(输入==null)
返回字符串。空;
bool containsQuote=false;
bool containsComma=false;
int len=输入长度;
对于(int i=0;i
您可以尝试这种方法。使用MemoryStream
追加新行,读取文件内容,然后将MemoryStream
中的所有字节写入文件:
string filePath = @"C:\Test\test.csv";
string csvLine = "value1; value2; value3" + Environment.NewLine;
byte[] csvLineBytes = Encoding.Default.GetBytes(csvLine);
using (MemoryStream ms = new MemoryStream())
{
ms.Write(csvLineBytes , 0, csvLineBytes.Length);
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
}
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Write))
{
ms.WriteTo(file);
}
}
您可以尝试这种方法。使用
MemoryStream
追加新行,读取文件内容,然后将MemoryStream
中的所有字节写入文件:
string filePath = @"C:\Test\test.csv";
string csvLine = "value1; value2; value3" + Environment.NewLine;
byte[] csvLineBytes = Encoding.Default.GetBytes(csvLine);
using (MemoryStream ms = new MemoryStream())
{
ms.Write(csvLineBytes , 0, csvLineBytes.Length);
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
}
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Write))
{
ms.WriteTo(file);
}
}