返回文件而不是写入文件

时间:2017-02-07 12:28:45

标签: c#

我有以下方法来创建csv文件 - 它在指定目录中创建一个文件。

如何修改此方法以返回创建的文件而不是写入磁盘?

public void CreateCSV(DataTable dt,string aTitle)
{

  string filePath = String.Concat(@"P:\folderX\",aTitle,@"-",this.guid,@".csv");
  string delimiter = ",";

  //size of the datatable
  int NumRows = dt.Rows.Count;
  int NumCols = dt.Columns.Count;

  StringBuilder sb = new StringBuilder();
  List<string> CsvRow = new List<string>();

  //try to deal with the headers first
  foreach(DataColumn c in dt.Columns)
  {
    CsvRow.Add(c.ColumnName.ToString());
  }
  sb.AppendLine(string.Join(delimiter,CsvRow));

  //now add the bulk of the data
  foreach(DataRow r in dt.Rows)
  {
    CsvRow.Clear();

    //go through each column adding to a list of strings
    foreach(DataColumn c in dt.Columns)
    {
      CsvRow.Add(r[c.ColumnName].ToString());
    }

    sb.AppendLine(string.Join(delimiter,CsvRow));
  }



  File.WriteAllText(filePath,sb.ToString());

}

0 个答案:

没有答案