-2

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>
htmlbran86
  • 203
  • 1
  • 3
  • 13
  • You say you've looked at videos and articles and are still struggling, but you didn't mention why. If you don't tell us exactly what you're stuck on, we could attempt to reproduce all of that content here you've already reviewed and still not improve your situation. – itsme86 Nov 21 '19 at 19:23
  • If you've tried something, please post the code of what you've tried and point out to where you're struggling. Then we can help. In the code you posted I don't see `App.config` being used anywhere. – Sach Nov 21 '19 at 19:23
  • And what exact issue you are facing here? – Chetan Nov 21 '19 at 19:23
  • https://stackoverflow.com/questions/1189364/reading-settings-from-app-config-or-web-config-in-net – Train Nov 21 '19 at 19:32
  • @itsme86 - My apologies, I'm struggling because I'm not sure of the best way to update my App.Config so things don't look so hard-coded in the actual program. – htmlbran86 Nov 21 '19 at 20:52
  • @Sach - I just edited my question to include the App.Config. Thanks! – htmlbran86 Nov 21 '19 at 20:52

2 Answers2

2

In Visual Studio:

  1. right-click your project,
  2. choose Add->New Item.
  3. In the search box, type "config".
  4. Choose "Application Configuration Item". This will add a boiler-plate XML file to your project named "App.config"
  5. Add an <appSettings></appSettings> element as a direct child of the main <configuration> node
  6. Within the appSetting element, create child elements that look like:
<add key="someKey" value ="Some value as a string, it could be a number, or whatever"/>
  1. Add a reference to System.Configuration to your project if there isn't one.
  2. In each file where you are going to access your app settings, add using System.Configuration; to the top of the file.

  3. To get the setting, use code like:

var someKeySetting = ConfigurationManager.AppSettings["someKey"];

At this point, someKeySetting will be a string that contains the setting you gave it in the config file. If the setting doesn't exist in the config file, then someKeySetting will be null. If you want to use numbers, dates, or enums, you will have to parse the string that results (preferably using the appropriate TryParse call.

Flydog57
  • 6,851
  • 2
  • 17
  • 18
1

You're going to want to put your values in the app.config file like so

<configuration> //this is probably already in your app.config file
  <appSettings>
    <add key="variable1Name" value="/mypathgoeshere/example" />
    ....
  </appSettings>
</configuration>

To access these variables you need these

Namespace: System.Configuration

Assemblies: System.Configuration.dll, System.Configuration.ConfigurationManager.dll

and then in your file you want to access it like this.

using System.Configuration;     

    public class Program
    {
        public static void Main()
        {
            string configvalue1 = ConfigurationManager.AppSettings["variable1Name"];
            //returns the value of "/mypathgoeshere/example"
        }
    }
Train
  • 3,420
  • 2
  • 29
  • 59