OraTest
is not a useful name. Call it OracleToCSVWriter
or something like that.
Mind the naming of variables etc: oda
is not very descriptive - adapter
would maybe be better.
Hardcoded username/password is rarely a good idea.
Why do you convert to string
in this line?:
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString()); sb.AppendLine(string.Join(",", fields));
I think the below would be sufficient:
sb.AppendLine(string.Join(",", row.ItemArray));
Even for such a small piece of code it is a good idea to split it up in meaningful parts (maybe: private string GetConnectionString() {...}
, private DataTable LoadData(OracleConnection connection) {...}
, WriteData(DataTable data) {...}
)
You should dispose OracleCommand
, OracleDataAdapter
as well as DataTable
just as you dispose OracleConnection
.
When writing to file, I would write directly to a stream, instead of first collect all data in memory:
using (StreamWriter writer = new StreamWriter("<Path>", false, Encoding.Unicode))
{
foreach (DataRow row in table.Rows)
{
writer.WriteLine(string.Join(", ", row.ItemArray));
}
}
That said You should be aware that when writing a CSV file, string and other data may contain commas (,) and that could break the column layout, so you'll have to encapsulate strings in quotation marks, which will complicate the writing a little bit. A way to go could be something like:
writer.WriteLine(string.Join(", ", row.ItemArray.Select(i => i is string? $"\"{i}\"" : i)));
or maybe:
writer.WriteLine(string.Join(", ", row.ItemArray.Select(i => $"\"{i}\"")));
(Not fully tested!)