I have been working on a file conversion project in C# using Visual Studio 2019. I have been asked to revise my code so that any file paths are replaced with variables that are called via the App.Config file. I am new to this method, as I was never taught how to do this before. I am looking for some guidance or examples if anyone could assist. I have tried any related articles or videos, but am still struggling. My code is below. I have updated any serve/db names to generic ones. Thanks in advance.
class Program
{
static void Main(string[] args)
{
string fromPath = string.Empty;
string toPath = string.Empty;
// set path where the source xls file is
string sourcePath = @"\\server\Data\subfolder\subfolder2\";
// determine target filename from today's date
string sourceFile = DateTime.Now.ToString("MM.dd.yy") + ".xls";
// determine if the target file exists
fromPath = sourcePath + sourceFile; // gives us the full path and filename to open
if (System.IO.File.Exists(fromPath))
{
// file exists, so process it
// make our output file
toPath = sourcePath + "import.csv";
// do the conversion to csv
CsvHelper csv = new CsvHelper();
csv.XlsToCsv(fromPath, toPath);
// renames one column to say 'idn_prod1'
var file1 = @"\\server\Data\subfolder\subfolder2\import.csv";
var lines = System.IO.File.ReadAllLines(file1);
var columnHeaders = lines[0];
var textToReplace = "idn_prod";
var newText = "idn_prod1";
var indexToReplace = columnHeaders
.LastIndexOf("idn_prod");//LastIndex ensures that you pick the second idn_prod
columnHeaders = columnHeaders
.Remove(indexToReplace, textToReplace.Length)
.Insert(indexToReplace, newText);//removes the second idn_prod and replaces it with the updated value.
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(file1))
{
sw.WriteLine(columnHeaders);
foreach (var str in lines.Skip(1))
{
sw.WriteLine(str);
}
sw.Flush();
}
// archive xls file to prevent buildup in this directory
if (Directory.Exists(@"\\server\Data\subfolder\subfolder2\"))
{
foreach (var file in new DirectoryInfo(@"C:\Users\myName\Documents\Projects\").GetFiles())
{
file.MoveTo($@"{ @"\\server\Data\subfolder\subfolder2\Archive"}\{file.Name}");
}
}
}
}
//Move data in CSV file to a DataTable
private static System.Data.DataTable GetDataTabletFromCSVFile(string csv_file_path = @"\\server\Data\subfolder\subfolder2\import.csv")
{
System.Data.DataTable csvData = new System.Data.DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
return null;
}
return csvData;
}
//import DataTable into Server and database table
static void InsertDataIntoSQLServerUsingSQLBulkCopy(System.Data.DataTable csvFileData)
{
using (SqlConnection dbConnection = new SqlConnection("Data Source=server;Initial Catalog=Database;Integrated Security=SSPI;"))
{
dbConnection.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = "Table";
foreach (var column in csvFileData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(csvFileData);
}
}
}
}
Below is my App.Config currently. Sorry for the issues prior.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings>
<!-- Name of the application-->
<add key="ApplicationName" value="xlsTocsv"/>
<!-- Archive directory for XLS files-->
<add key="MoveTo"
value="@\\server\Data\subfolder\subfolder2\Archive"/>
<!-- Server Name for import-->
<add key="Data Source" value="Server"/>
</appSettings>
</configuration>