c# - 使用指定的文件名和路径创建一个 csv 文件

标签 c# csv

我知道这应该很简单,但我对 C# 还很天真。我有以下对象生成为 csv。并且我能够使用 here 方法成功生成一个 csv 字符串

[Serializable]
public class UserSession
{
    public string UserName { get; set; }
    public string UserGuid { get; set; }
    public string MachineGuid { get; set; }
    public Guid SessionGuid { get; set; }
    public DateTime LoginTime { get; set; }
    public DateTime? LogOffTime { get; set; }
    public TimeSpan? DesktopReady { get; set; }
    public bool IsReadable { get; set; }
    public int SessionId { get; set; }
}

现在我想把这个文件保存在一个指定的路径中(例如:

c://csvfolder/{myFilename}.csv

任何人都可以建议一种将此 csv 文件写入 'myFilename.csv' 并将其保存在 c# 中的 c://csvfolder 中的方法>??

最佳答案

这应该很简单。看起来您有一个通用类,可以将您的对象序列化为字符串缓冲区。

剩下的就是获取包含 CSV 数据的字符串并将其写入文件。幸运的是,这在 C# 中非常简单:

string path = @"c:\csvfolder\myFilename.csv";

// assuming there's a UserSession object called userSessionObject..
string csvData = ToCsv<UserSession>(",", new [] {userSessionObject});
File.WriteAllText(path, csvData);

关于c# - 使用指定的文件名和路径创建一个 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36325781/

相关文章:

c# 错误 : “Could Not Find Installable ISAM” in converting Excel file into . CSV 文件

csv - PowerShell错误:Import-CSV无法打开文件

c - 从标准输入输入文件时无限读取输入

c# - WPF 用户控件项未显示

c# - 使用 C# 以编程方式操作 PostBackUrl

c# - 使用 c# 和 opencl 的内存对象分配失败

c# - 许多 WebReferences 使用相同的类

php - 将 CSV 转换为 PHP 数组 - 结束行问题 (CR LF)

python - 追加到列表列表中的一个列表也追加到所有其他列表

c# Soap 客户端问题 - 找到一个以上契约(Contract)的端点配置