- 引用“System.Windows.Forms”
- Using指令:
using System.IO;
using System.Windows.Forms;
- 代码块:
/// <summary>
/// 保存二维double数组至csv文件
/// </summary>
/// <param name="input">输入二维double数组</param>
/// <param name="filename">待保存文件名</param>
private void Savecsv(double[,] input, string filename = "Output")
{
// This text is always added, making the file longer over time
// if it is not deleted.
string path = System.Windows.Forms.Application.StartupPath + "\\" + filename + ".csv";
//string s = path.Substring(0, path.LastIndexOf('\\'));
//Directory.CreateDirectory(s);//如果文件夹不存在就创建它(用于将数据保存至指定文件夹)
using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))//创建或追加,用于新增内容时
//using (System.IO.StreamWriter sw = System.IO.File.CreateText(path))//创建或覆盖,用于覆盖内容时
{
//逐行
for (int i = 0; i < input.GetLength(0); i++)
{
//逐列
for (int j = 0; j < input.GetLength(1); j++)
{
sw.Write(input[i, j] + ",");
}
sw.WriteLine();
}
}
}
以下为旧实现方式:
// <summary>
/// 保存二维double数组至csv文件
/// </summary>
/// <param name="input">输入二维数组</param>
/// <param name="filename">待保存文件名</param>
public void Savecsv(double[,] input, string filename = "output")
{
//打开文件流
FileStream fs;
OpenFileStream(out fs, Application.StartupPath + "\\" + filename + ".csv");
//写入数据至数据流
StreamWriter sw = new StreamWriter(fs);
WriteStream(input, ref sw);
//关闭数据流和文件流
sw.Close();
fs.Close();
}
/// <summary>
/// 打开文件流
/// </summary>
/// <param name="fs">文件流</param>
/// <param name="path">路径</param>
public void OpenFileStream(out FileStream fs, string path)
{
//判断指定文件路径是否存在
if (!File.Exists(path))
{
//指定文件路径不存在,则创建文件流
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
}
else
{
//指定文件路径存在,则打开文件流
fs = new FileStream(path, FileMode.Open, FileAccess.Write);
}
}
/// <summary>
/// 写入数据至数据流
/// </summary>
/// <param name="input">输入二维double数组</param>
/// <param name="sw">流</param>
public void WriteStream(double[,] input, ref StreamWriter sw)
{
//逐行
for (int i = 0; i < input.GetLength(0); i++)
{
//逐列
for (int j = 0; j < input.GetLength(1); j++)
{
sw.Write(input[i, j] + ",");
}
sw.WriteLine();
}
}