Skip to content

Instantly share code, notes, and snippets.

@beached
Created November 6, 2018 12:54
Show Gist options
  • Save beached/67c92a9600bc5df133af8e687672f08e to your computer and use it in GitHub Desktop.
Save beached/67c92a9600bc5df133af8e687672f08e to your computer and use it in GitHub Desktop.
using System;
using System.IO;
namespace CSVExport {
public class CSVExport {
private static string CsvEscape( object value ) {
if(value is null) {
return string.Empty;
}
string str = value.ToString( );
return @"""" + str.Replace( @"""", @"""""" ) + @"""";
}
private static void StartCSV<T>( T obj, string file_path, bool overwrite = false ) {
if(File.Exists( file_path ) && !overwrite) {
return;
}
using(var fs = File.CreateText( file_path )) {
bool first = true;
foreach(var prop in typeof( T ).GetProperties( )) {
if(Attribute.IsDefined( prop, typeof( System.ComponentModel.BrowsableAttribute ) )) {
continue;
}
string item = string.Empty;
if(!first) {
item += @",";
}
first = false;
item += $@"{CsvEscape( prop.Name )}";
fs.Write( item );
}
fs.Write( "\r\n" );
fs.Flush( );
}
}
public static void AppendCSV<T>( T obj, string file_path ) {
var start_time = DateTime.Now;
try {
StartCSV( obj, file_path );
using(var fs = File.AppendText( file_path )) {
bool first = true;
foreach(var prop in typeof( T ).GetProperties( )) {
if(Attribute.IsDefined( prop, typeof( System.ComponentModel.BrowsableAttribute ) )) {
continue;
}
string item = string.Empty;
if(!first) {
item += @",";
}
first = false;
item += $@"{CsvEscape( prop.GetValue( obj, null ) )}";
fs.Write( item );
}
fs.Write( "\r\n" );
fs.Flush( );
}
} finally {
System.Diagnostics.Debug.WriteLine( $@"AppendCSV to {file_path} took {new FormattedTimeSpan( DateTime.Now - start_time )}" );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment