我想在第一行插入新的两行而不影响CSV文件中的现有数据。
E.g: 现有的CSV文件格式:
Name Address Value
--------------------------------
abc India 123
XXX USA 456
需要在现有CSV文件列标题之前插入新行。 E.g:
Line1-A ---> Need to add this line before column.
Line2-B ---> Need to add this line before column.
Name Address Value
--------------------------------
abc India 123
XXX USA 456
我创建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; }
}
}
答案 0 :(得分:0)
您可以尝试这种方法。使用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);
}
}