Skip to content

Instantly share code, notes, and snippets.

@sawilde
Created April 19, 2012 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sawilde/2419627 to your computer and use it in GitHub Desktop.
Save sawilde/2419627 to your computer and use it in GitHub Desktop.
load in a CSV file and wrap any field that isn't already in quotes with quotes
class Program
{
/// <summary>
/// load in a CSV file and wrap any field that isn't in quotes with quotes
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
var reader = File.OpenText(Path.Combine(Directory.GetCurrentDirectory(),args[0]));
var writer = new StreamWriter(Path.Combine(Directory.GetCurrentDirectory(), args[1]));
var data = reader.ReadLine();
while (!string.IsNullOrEmpty(data))
{
// split the line
var elem = data.Split(new[]{','});
var list = new List<string>();
for (var i = 0; i < elem.Count(); i++)
{
var sample = elem[i];
// check that if we start with a quote we end with one i.e. we
// haven't accidently split on a comma that was encapsulated by "'s
if (FieldStartsWithQuote(sample))
{
while (elem[i][elem[i].TrimEnd().Count()-1] != '"')
{
sample += "," + elem[i + 1];
i++;
}
}
list.Add(sample);
}
for (var i = 0; i < list.Count; i++)
{
// wrap fields without quotes
if (!FieldStartsWithQuote(list[i]))
list[i] = "\"" + list[i] + "\"";
}
writer.WriteLine(string.Join(",", list).TrimEnd(','));
data = reader.ReadLine();
}
writer.Close();
reader.Close();
}
private static bool FieldStartsWithQuote(string sample)
{
return (!string.IsNullOrEmpty(sample)) && (sample.TrimStart()[0] == '"');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment